Mybatis学习笔记
Mybati使用笔记
创建一个maven项目
导入依赖
依赖查询地址:https://mvnrepository.com/artifact/org.mybatis/mybatis
Mybatis中网官方文档:https://mybatis.net.cn/getting-started.html
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
编写Mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<!--引入外部配置文件-->
<properties resource="jdbc.properties"/> <!--xml中每个标签都规定了顺序--><!---->
<settings><!--控制mybatis全局行为-->
<!--设置mybatis输出日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 控制日志 把日志输出到控制台-->
</settings>
<typeAliases><!--类型别名--><!--可以给实体类起别名-->
<typeAlias type="com.yuantaopowermode.domain.Student" alias="Student"/>
</typeAliases>
<!--配置插件--><!--放在环境前面-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
<environments default="development">
<environment id="development"><!--环境 默认选择-->
<transactionManager type="JDBC"/><!--事务管理器-->
<dataSource type="POOLED"><!--数据源-->
<property name="driver" value="${jdbc.driver}"/><!--com.mysql.jdbc.Driver-->
<property name="url"
value="${jdbc.url}"/><!--jdbc:mysql://localhost:3306/test?useSSL=ture&useUnicode=true&characterEncoding=utf-8-->
<!--useSSL=ture 设置安全连接,防止因为JDBC版本与mysql版本不兼容发生错误-->
<!--useUnicode=true&characterEncoding=utf-8 指定字符的编码格式和解码格式-->
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--sql mapper(sql映射文件)的位置-->
<mappers>
<!-- <mapper resource="com/yuantaopowermode/dao/StudentDao.xml"/><!–可以有多个–>-->
<!--可以使用package 一次性导入包中所有的xml文件-->
<!--要求 mapper文件必须和接口在同一目录
mapper文件名称需要和接口名称一样-->
<package name="com.yuantaopowermode.dao"/>
</mappers>
</configuration>
jdbc.properties配置文件
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
jdbc.initialSize=5
jdbc.maxActive=10
编写Mybatis工具
从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或 file:// URL 构造的输入流。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
为了方便,编写工具类获取SqlSession
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
// SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
编写代码
创建实体类
ublic class Student {
//定义属性名 目前要求是属性名和列明一样
private Integer id;
private String name;
private String email;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Student() {
}
public Student(Integer id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
编写mapper接口
//接口操作student表
public interface StudentDao {
//查询student表的所有数据
public List<Student> selectStudents();
//插入操作
public int insertStudent(Student student);
/*
* 参数的使用
* 1、一个简单的参数*/
public Student selectStudentById(Integer id);
/* 2、多个参数,在形参定义面前加入 @Param("自定义参数名称")*/
public List<Student> listStudent(@Param("myname") String name, @Param("myage") int age);
/* 2、多个参数,另一种方式传递参数*/
public List<Student> listStudent22(String name, int age);
public Student resultmap(Integer id);
}
编写mapper.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace = 绑定一个对应的dao/mapper接口-->
<!--相当于实现了这个接口-->
<mapper namespace="com.yuantaopowermode.dao.StudentDao">
<!--查询语句 相当于是重写了接口中的方法,
id 相当于重写方法的名字
resultType 返回结果的类型,需要写全限定名
parameterType 参数类型
-->
<select id="selectStudents" resultType="com.yuantaopowermode.domain.Student">
select * from student
</select>
<!--查询语句 相当于是重写了接口中的方法,
方法中有参数 id
在sql语句中可以通过#{参数名}的防止直接获取
-->
<select id="selectStudentById" parameterType="int" resultType="com.yuantaopowermode.domain.Student">
select * from student where id = #{id}
</select>
<!--插入语句 相当于是重写了接口中的方法,
方法中有参数 Student 类,通过#{参数名}的方式直接获取
-->
<insert id="insertStudent">
insert into student values(#{id},#{name},#{email},#{age})
</insert>
<select id="listStudent" resultType="com.yuantaopowermode.domain.Student">
select * from student where name = #{myname} or age = #{myage}
</select>
<select id="listStudent22" resultType="com.yuantaopowermode.domain.Student">
select * from student where name = #{arg0} or age = #{arg1}
</select>
<!-- 万能的Map,
可以创建一个Map对象,将其作为参数传递
也可以在.xml中创建一个Map的返回类型,作为返回的结果类型-->
<resultMap id="resultmap" type="Student"><!--结果集映射-->
<!--column 数据库中的字段 property 实体类中的属性-->
<result column="id" property="id"></result> <!--只需要映射不同的字段-->
<result column="name" property="name"></result>
<result column="email" property="email"></result>
<result column="age" property="age"></result>
</resultMap>
<!-- 解决数据库中字段和实体类的属性不同的问题 方式一 起别名 方式二 结果集映射-->
<select id="resultmap" resultMap="resultmap">
select * from student where id = #{id}
</select>
</mapper>
测试
@Test //查询测试
public void test3() {
//获得SqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//执行sql
StudentDao dao = sqlSession.getMapper(StudentDao.class);
//调用方法
System.out.println(dao.selectStudentById(1001));
//关闭SqlSession
sqlSession.close();
}
@Test //插入测试
public void test3() {
//获得SqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//执行sql
StudentDao dao = sqlSession.getMapper(StudentDao.class);
//调用方法
dao.insertStudent(new Student(1,"name","123@qq.com",18));
//提交事务 -----------所有的 增删改 都需要提交事务
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
注意点
- 每一个mapper配置文件都需要在mapper核心配置文件注册
- 资源过滤问题
<build>
<resources>
<resource>
<directory>src/main/java/</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
- 绑定接口错误
- 方法名不对
- 返回类型不对
- 所有的增删改都需要提交事务
以上只是简单介绍,参考狂神视频:https://www.bilibili.com/video/BV1NE411Q7Nx?p=9&spm_id_from=pageDriver
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!