Mybatis笔记
Mybatis
环境:
- JDK 1.8
- Mysql 5.7
- maven 3.6.1
- IDEA
回顾:
- JDBC
- Mysql
- Java基础
- Maven
- Junit
SSM(Spring+SpringMVC+MyBatis)框架:配置文件,最好方式:看官网文档
Mybatis中文官方文档:mybatis – MyBatis 3 | 简介
1、简介
1.1 什么是Mybatis
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
如何获得Mybatis?
-
maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency>
1.2 持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(jdbc),io文件持久化
为什么需要持久化?
- 内存断电即失,有一些对象不能丢掉
- 内存贵
1.3 持久层
Dao层,Service层,Controller层
层:
- 完成持久化工作的代码块
- 层 界限十分明显
1.4 为什么需要Mybatis
- 方便
- 传统的JDBC代码太复杂,简化,框架,自动化
- 帮助程序员将数据存入到数据库中
2、第一个Mybatis程序
思路:搭建环境 ---> 导入jar包 ---> 编写代码 ---> 测试
2.1 搭建环境
搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'kxy','123456'),
(2,'张三','123456'),
(3,'李四','123456');
新建项目
-
新建一个普通的maven项目
-
删除src目录
-
导入maven依赖
<!--导入依赖--> <dependencies> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!--mybatis--> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies>
2.2 创建一个模块
-
编写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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
-
编写mybatis工具类
//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(); } } public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
2.3 编写代码
-
实体类
package com.kong.pojo; public class User { private int id; private String name; private String pwd; public User() {} public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
-
Dao/Mapper接口
public interface UserDao { List<User> getUserList(); }
-
接口实现类,由原来的UserDaoImpl转变为一个 Mapper 配置文件
<?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.kong.dao.UserDao"> <!--select查询语句--> <select id="getUserList" resultType="com.kong.pojo.User"> select * from mybatis.user </select> </mapper>
注意:
-
namespace 对应Mapper接口名
-
id值为Mapper 接口中的方法名称
-
parameterType 值表示Mapper 对应方法的入参类型
-
resultType 值则对应了Mapper 接口表示的返回值类型或者返回结果集的元素类型。
-
2.4 测试
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.kong.dao.UserDao is not known to the MapperRegistry.
核心配置文件中注册Mappers
通过SqlSession.getMapper(XXXMapper.class)
方法,MyBatis 会根据相应的接口声明的方法信息,通过动态代理机制生成一个Mapper 实例,
@Test
public void test() {
//第一步:获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//第二步:执行sql
//方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
可能遇到的问题:
- 配置文件没有注册
- 绑定接口错误
- 方法名不对
- 返回类型不对
- maven导出资源问题
补:Mybatis执行流程
mybatis初始化要经过简单的以下几步:
- 调用SqlSessionFactoryBuilder对象的build(inputStream)方法;
- SqlSessionFactoryBuilder会根据输入流inputStream等信息创建XMLConfigBuilder对象;
- SqlSessionFactoryBuilder调用XMLConfigBuilder对象的parse()方法;
- XMLConfigBuilder对象返回Configuration对象;
- SqlSessionFactoryBuilder根据Configuration对象创建一个DefaultSqlSessionFactory对象;
- SqlSessionFactoryBuilder返回 DefaultSqlSessionFactory对象sqlSessionFactory给Client,供Client使用。
3、CRUD
3.1 namespace
namespace中的包名要和Dao/Mapper 接口的包名一致
3.2 select
选择,查询语句
- id:就是对应的namespace中的方法名;
- resultType:sql语句执行的返回值类型;
- parameterType:参数类型;
-
编写接口
//根据id查询用户 User getUserById(int id);
-
编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.kong.pojo.User"> select * from mybatis.user where id = #{id} </select>
-
测试
@Test public void testGetUserById() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); }
3.3 insert
<!--对象中的属性可以直接取出来-->
<insert id="addUser" parameterType="com.kong.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd})
</insert>
3.4 update
<update id="updateUser" parameterType="com.kong.pojo.User">
update mybatis.user set name=#{name}, pwd=#{pwd} where id=#{id}
</update>
3.5 delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
注意点:
-
增删改需要提交事务!
sqlSession.commit();
3.6 分析错误
- 标签不要匹配错
- resource 绑定 mapper,需要使用路径"/",不是"."
- 程序配置文件必须符合规范
- NullPointerException,没有注册到资源
- 输出的xml文件中存在中文乱码问题
- maven资源没有导出问题
3.7 万能的Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
int addUser2(Map<String, Object> map);
<!--对象中的属性可以直接取出来, 传递 map 的key-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id, name, pwd) values (#{userId},#{userName},#{password})
</insert>
@Test
public void addUser2() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("userId",5);
map.put("userName","hehe");
map.put("password","123123");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可 parameterType="map"
对象传递参数,直接在sql中取对象属性即可 parameterType="com.kong.pojo.User"
只有一个基本类型参数情况下,可以直接在sql中取 parameterType="int"
多个参数用Map,或者注解
3.8 思考题
模糊查询怎么写?
-
Java代码执行的时候,传递通配符 % %
List<User> userList = mapper.getUserLike("h%");
-
在sql拼接中使用通配符
select * from mybatis.user where name like #{value}"%"
4、配置解析
4.1 核心配置文件
-
mybatis-config.xml
-
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
4.2 环境配置(environments)
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
学会使用配置多套运行环境
Mybatis默认的事务管理器是 JDBC,连接池是 POOLED
<environments default="development">
<environment id="development">
<!--
JDBC–这个配置直接简单使用了JDBC的提交和回滚设置。它依赖于从数据源得到的连接来管理事务范围。
MANAGED–这个配置几乎没做什么。它从来不提交或回滚一个连接。而它会让容器来管理事务的整个生命周期(比如Spring或JEE应用服务器的上下文)。
-->
<transactionManager type="JDBC"/>
<!--
UNPOOLED–这个数据源的实现是每次被请求时简单打开和关闭连接
POOLED–mybatis实现的简单的数据库连接池类型,它使得数据库连接可被复用,不必在每次请求时都去创建一个物理的连接。
JNDI – 通过jndi从tomcat之类的容器里获取数据源。
-->
<dataSource type="POOLED">
<!--
如果上面没有指定数据库配置的properties文件,那么此处可以这样直接配置
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test1"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
-->
<!-- 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
<!-- 我再指定一个environment -->
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- 与上面的url不一样 -->
<property name="url" value="jdbc:mysql://localhost:3306/demo"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
4.3 属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
-
编写一个配置文件,db.properties
driver = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT username = root password = 123456
-
在核心配置文件中引入
<!-- 引入外部配置文件 --> <!-- 方法一: 从外部指定properties配置文件 <properties resource="db.properties"></properties> --> <!-- 方法二: 直接配置为xml --> <properties> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test1"/> <property name="username" value="root"/> <property name="password" value="111111"/> </properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果一个属性在不只一个地方进行了配置(两种方法都同时配置了),那么,MyBatis 将按照下面的顺序来加载:首先会加载文件中的xml配置,其次是加载外部指定的properties,最后加载Java Configuration的配置,后加载的配置会覆盖先加载的配置。所以,最终应用配置时Configuration配置优先级最高,其次是外部的properties配置文件,最后是当前xml中的配置。
4.4 类型别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字
- 它仅用于 XML 配置,意在降低冗余的全限定类名书写
<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.kong.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
扫描实体类的包,它的默认别名就为这个类的 类名 首字母小写!
<!--可以给实体类起别名-->
<typeAliases>
<package name="com.kong.pojo"/>
</typeAliases>
在实体类比较少的情况下,使用第一种方式
如果实体类比较多,建议使用第二种
第一种可以DIY别名,第二种则不行(相对来说,但是可以使用注解起别名)
@Alias("author")
public class Author {
...
}
4.5 设置
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
4.6 其他配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
4.7 映射器(mappers)
注册绑定我们的mapper文件
方式一:
<!--每一个Mapper.xml都需要在mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/kong/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<!--每一个Mapper.xml都需要在mybatis核心配置文件中注册-->
<mappers>
<mapper class="com.kong.dao.UserMapper"/>
</mappers>
注意点:
- 接口和它的Mapper配置文件必须同名
- 接口和它的配置文件必须在一个包下
方式三:使用扫描包注入绑定
<!--每一个Mapper.xml都需要在mybatis核心配置文件中注册-->
<mappers>
<package name="com.kong.dao"/>
</mappers>
注意点:
- 接口和它的Mapper配置文件必须同名
- 接口和它的配置文件必须在一个包下
4.8 生命周期和作用域
作用域和生命周期是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory:
-
说白了可以想象为:数据库连接池
-
SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
-
因此 SqlSessionFactory 的最佳作用域是应用作用域
-
有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。
SqlSession:
- 连接到连接池的一个请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要赶紧关闭,否则资源被占用
这里面每一个Mapper,就代表一个业务
5、解决属性名和字段名不一致问题
5.1 问题
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
public class User {
private int id;
private String name;
private String password;
}
测试结果出现问题
解决方法:
-
起别名
<select id="getUserById" parameterType="int" resultType="com.kong.pojo.User"> select id,name,pwd as password from mybatis.user where id = #{id} </select>
5.2 resultMap
结果集映射
id name pwd
id name password
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段 property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
resultMap
元素是 MyBatis 中最重要最强大的元素- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
- 如果这个世界总是这么简单就好了。
6、日志
6.1 日志工厂
如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手
曾经:sout、debug
现在:日志工厂
- SLF4J
- LOG4J(deprecated since 3.5.9) 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【掌握】
- NO_LOGGING
在mybatis中具体使用哪一个日志,在设置中设定。
STDOUT_LOGGING标准日志输出
6.2 LOG4J
-
先导入LOG4J的包
<!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
-
log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码 log4j.rootLogger=DEBUG,console,file #控制台输出的相关设置 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n #文件输出的相关设置 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/kong.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n #日志输出级别 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
-
配置log4j为日志实现
<settings> <setting name="logImpl" value="LOG4J"/> </settings>
-
测试
7、分页
思考:为什么要分页?
- 减少数据的处理量
7.1、使用Limit分页
语法:select * from user limit startIndex,pageSize;
使用mybatis实现分页,核心sql
-
接口
//分页 List<User> getUserByLimit(Map<String, Integer> map);
-
mapper.xml
<!--分页--> <select id="getUserByLimit" parameterType="map" resultMap="UserMap"> select * from mybatis.user limit #{startIndex},#{pageSize} </select>
-
测试
@Test public void getUserByLimit() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String,Integer> map = new HashMap<String, Integer>(); map.put("startIndex",0); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7.2、RowBounds分页
我们除了使用Limit在SQL层面实现分页,也可以使用RowBounds在Java代码层面实现分页,当然此种方式作为了解即可。我们来看下如何实现的!
-
接口
//分页2 List<User> getUserByRowBounds();
-
mapper.xml
<select id="getUserByRowBounds" resultType="user"> select * from user </select>
-
测试:使用RowBounds类
@Test public void testUserByRowBounds() { SqlSession session = MybatisUtils.getSession(); int currentPage = 2; //第几页 int pageSize = 2; //每页显示几个 RowBounds rowBounds = new RowBounds((currentPage-1)*pageSize,pageSize); //通过session.**方法进行传递rowBounds,[此种方式现在已经不推荐使用了] List<User> users = session.selectList("com.kuang.mapper.UserMapper.getUserByRowBounds", null, rowBounds); for (User user: users){ System.out.println(user); } session.close(); }
7.3、分页插件
PageHelper
了解即可
8、使用注解开发
8.1 面向接口编程
三个面向区别
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性和方法;
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现;
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构;
8.2 使用注解开发
-
注解在接口上实现
@Select("select * from user") List<User> getUsers();
-
在核心配置文件中绑定接口
<!--绑定接口--> <mappers> <mapper class="com.kong.dao.UserMapper"/> </mappers>
-
测试
本质:反射机制实现
底层:动态代理
mybatis详细的执行流程:
8.3 CRUD
我们可以在工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
//查询所有用户
@Select("select * from user")
List<User> getUsers();
//方法存在多个参数,所有参数前面必须加上@Para注解
//User getUserById(@Param("id") int id, @Param("name") String name);
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
@Insert("insert into user(id, name, pwd) values (#{id}, #{name}, #{password})")
int addUser(User user);
@Update("update user set name=#{name}, pwd=#{password} where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
测试
注意:我们必须要将接口注册绑定到我们的核心配置文件中
关于@Param() 注解
- 基本类型参数和String类型参数,需要加上
- 引用类型不需要加
- 如果只有一个基本类型,可以忽略,但是建议加上
- 在SQL中引用的就是 @Param() 中设定的属性名
#{} ${} 区别: #{} 可以防止sql注入
9、Lombok
使用步骤:
-
在IDEA中安卓Lombok插件
-
在项目中导入Lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency>
-
在实体类上加注解
@Data @AllArgsConstructor @NoArgsConstructor
常用Lombok注解:
@Data:无参构造、get、set、tostring、hashcode、equals
@AllArgsConstructor:有参构造
@NoArgsConstructor:无参构造
@EqualsAndHashCode
@ToString
@Getter
@Setter
10、多对一处理
- 多个学生对应一个老师
- 对于学生这边而言,关联 多个学生关联一个老师 【多对一】
- 对于老师而言,集合 一个老师有多个学生 【一对多】
SQL
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
测试环境搭建
- 导入Lombok
- 新建实体类 Teacher,Student
- 建立Mapper接口
- 建立Mapper.xml文件
- 在核心配置文件中绑定注册Mapper接口或文件【方式选一个】
- 测试查询是否成功
按照查询嵌套处理
<!--
思路:
1.查询所有学生的信息
2.根据查出来的学生的tid,寻找对应的老师 子查询
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,我们需要单独处理 对象:association 集合:collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{tid}
</select>
按照结果嵌套处理
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid, s.name sname, t.name tname
from mybatis.student s, mybatis.teacher t
where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
回顾Mysql多对一查询方式:
- 子查询
- 联表查询
11、一对多处理
比如:一个老师拥有多个学生
对于老师而言就是一对多的关系
环境搭建
和刚才一样,实体类变化
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
按照查询嵌套处理
<!--按查询嵌套-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid = #{id}
</select>
按照结果嵌套处理
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname, t.id tid
from mybatis.student s, mybatis.teacher t
where s.tid=tid and tid = #{tid};
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--集合-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
小结
- 关联 - association 【多对一】
- 集合 - collection 【一对多】
- javaType & ofType
- javaType 用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
12、动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
搭建环境
CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8;
创建一个基础工程
-
导包
-
编写配置文件
-
编写实体类
@Data public class Blog { private int id; private String title; private String author; private Date createTime; private int views; }
-
编写实体类对应的Mapper接口 和 Mapper.xml 文件
IF
最常见情景是根据条件包含 where 子句的一部分。
-
接口
//查询博客 List<Blog> queryBlogIF(Map map);
-
Mapper.xml
<select id="queryBlogIF" parameterType="map" resultType="blog"> select * from mybatis.blog where 1=1 <if test="title != null"> and title = #{title} </if> <if test="author != null"> and author = #{author} </if> </select>
-
测试
@Test public void queryBlogIF() { SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Map map = new HashMap(); //map.put("title","Java"); map.put("author","狂神说"); List<Blog> blogs = mapper.queryBlogIF(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
choose (when, otherwise)
注意:只会选择一个 when,当都不成立时,进入 otherwise
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
trim (where, set)
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
foreach
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
SQL片段
有时候,我们可能会将一些公共的部分抽取出来,方便复用
-
使用sql标签抽取公共部分
<sql id="if-title-author"> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
-
在需要使用的地方使用 include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <include refid="if-title-author"></include> </where> </select>
注意事项:
- 最好基于单表来定义SQL片段
- 不要存在where标签
所谓的动态SQl,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了!
13、缓存
13.1、简介
查询 : 连接数据库,耗资源
一次查询的结果,给他暂存一个可以直接取到的地方 --> 内存:缓存
我们再次查询的相同数据的时候,直接走缓存,不走数据库了
- 什么是缓存[Cache]?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
- 什么样的数据可以使用缓存?
- 经常查询并且不经常改变的数据 【可以使用缓存】
13.2、Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存,缓存可以极大的提高查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
13.3、一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试步骤:
-
开启日志
-
测试在一个Session中 查询两次记录
-
查看日志输出
缓存失效的情况:
-
查询不同的东西
-
增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
-
查询不同的Mapper.xml
-
手动清理缓存
小结:一级缓存默认是开启的,只在一次sqlSession中有效,也就是拿到连接到关闭连接这个区间段!
一级缓存相当于一个map
13.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个命名空间,对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查询出的数据会放在自己对应的缓存(map)中
一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
步骤:
-
mybatis-config.xml开启全局缓存
<!--开启全局缓存--> <setting name="cacheEnabled" value="true"/>
-
在要使用二级缓存的Mapper中开启
<cache/>
也可以自定义一些参数
<!--在当前Mapper.xml中 使用二级缓存--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
-
测试
小结:
- 只要开启了二级缓存,在同一个Mapper.xml下就有效
- 所有数据都会先放在一级缓存中
- 只有当会话提交,或者关闭的时候,才会提交到二级缓存中
13.5、缓存原理
13.6、自定义缓存-Ehcache
-
先导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache --> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.2.1</version> </dependency>
-
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <diskStore path="./tmpdir/Tmp_EhCache"/> <defaultCache eternal="false" maxElementsInMemory="10000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="1800" timeToLiveSeconds="259200" memoryStoreEvictionPolicy="LRU"/> <cache name="cloud_user" eternal="false" maxElementsInMemory="5000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="1800" timeToLiveSeconds="1800" memoryStoreEvictionPolicy="LRU"/> </ehcache>
-
在Mapper中指定我们的ehcache实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
常见面试题:
1、#{} 和 ${} 的区别?
- ${} 是 Properties 文件中的变量占位符,可以用于标签属性值和sql内部,属于静态文本替换,比如${driver}会被静态替换为
com.mysql.jdbc. Driver
-
{} 是 sql 的参数占位符,MyBatis 会将 sql 中的 #{} 替换为 ?号,在sql执行前会使用 PreparedStatement 的参数设置方法,按序给 sql 的 ?号占位符设置参数值。
2、Dao接口的工作原理
Dao接口即Mapper接口,
- 接口全限名:映射文件中 namespace的值
- 接口方法名:Mapper中 Statement 的 id 值
- 接口方法参数:传递给 sql 的参数
Mapper接口没有实现类,当调用接口方法时,接口全限名+方法名拼接的字符串可唯一定位一个 Mapper Statement。
Dao接口里的方法,是不能重载的,因为是全限名+方法名确定Statement。但是,源码有漏洞,当接口中存在一个无参方法和一个重载的有参方法时,Mapper文件 Statement id 唯一,此时可以执行成功。
/**
* Mapper接口里面方法重载
*/
public interface StuMapper {
List<Student> getAllStu();
List<Student> getAllStu(@Param("id") Integer id);
}
<select id="getAllStu" resultType="com.pojo.Student">
select * from student
<where>
<if test="id != null">
id = #{id}
</if>
</where>
</select>
Dao接口的工作原理是JDK动态代理,mybatis运行时会使用JDK动态代理为Dao接口生成代理proxy对象,代理对象proxy会拦截接口方法,转而执行MapperStatement多代表的sql,然后返回结果。
3、在Mapper中如何传递多个参数?
-
{0}代表第一个参数,#{1}代表第二个参数.....
-
使用
@Param
注解 -
将多个参数封装为Map
<!--对象中的属性可以直接取出来, 传递 map 的key--> <insert id="addUser2" parameterType="map"> insert into mybatis.user (id, name, pwd) values (#{userId},#{userName},#{password}) </insert>
4、动态 sql
-
if 条件判断
<if test="title != null"> AND title like #{title} </if>
-
choose, when, otherwise
<choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose>
-
trim (where, set)
where:删除多余的 and
<where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </where>
set:删除多余的 ,号
<set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set>
-
foreach
<foreach item="item" index="index" collection="list" open="ID in (" separator="," close=")" nullable="true"> #{item} </foreach>
源码分析
总体框架设计
配置好 Mybatis 的 XXXMapper.xml 文件后,通过 SqlSession.getMapper(XXXMapper.xml)
方法,Mybatis 会根据相应的接口声明的方法信息,通过动态代理机制生成一个Mapper实例,使用Mapper接口中的某一方法时,Mybatis会根据这个方法的方法名和参数类型,确定 Statement Id
,底层通过SqlSession.select(statementId, parameterObject)
,来实现对数据库的操作。
// mybatis初始化
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行SQL语句
List list = sqlSession.selectList("com.foo.bean.BlogMapper.queryAllBlogInfo");
初始化基本过程
SqlSessionFactoryBuilder
根据传入的数据流生成 Configuration
对象,然后根据 Configuration
对象创建默认的 SqlSessionFactory
实例。

mybatis初始化要经过简单的以下几步:
- 调用
SqlSessionFactoryBuilder
对象的build(inputStream)
方法; SqlSessionFactoryBuilder
会根据输入流 inputStream等信息创建XMLConfigBuilder
对象;SqlSessionFactoryBuilder
调用XMLConfigBuilder对象的parse()
方法;XMLConfigBuilder
对象返回Configuration
对象;SqlSessionFactoryBuilder
根据Configuration
对象创建一个DefaultSessionFactory
对象;SqlSessionFactoryBuilder
返回DefaultSessionFactory
对象给Client,供Client使用。
sqlSession执行流程
获得 sqlSessionFactory
对象以后,调用 openSession()
方法,既可以获得 sqlSession
对象。
openSession()
实际上是调用 openSessionFromDataSource
方法
public SqlSessionopenSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(),null, false);
}
当获取 数据源DataSource
并创建数据库连接对象Connection
,获取事务工厂TransactionFactory
,并创建事务对象Transaction
,最后创建 sqlSession
对象。
当我们执行dao里面方法的时候,其实是对应mapperProxy在代理。通过 SqlSession
从 Configuration
中获取,最终也是由 MapperProxyFactory
获取。
Sqlsession
对数据库的操作都是通过 Executor
来完成的。
MyBatis 传递参数
传递一个参数
例如:
UserModel getByName(String name);
直接使用 #{name}
传递一个Map参数
例如:
List<UserModel> getByMap(Map<String,Object> map);
使用 #{map中的key}
# Map<String, Object> map = new HashMap<>();
# map.put("id", 1L);
# map.put("name", "张学友");
SELECT * FROM t_user WHERE id=#{id} OR name = #{name}
传递一个Java对象
例如:
List<UserModel> getListByUserFindDto(UserFindDto userFindDto);
标签使用 parameterType
,并使用 #{属性名}
获取
例如:
<select id="getListByUserFindDto" parameterType="com.kong.dao.UserFindDto" resultType="com.kong.pojo.UserModel">
SELECT * FROM t_user WHERE id=#{userId} OR name = #{userName}
</select>
传递多个参数
例如:
UserModel getByIdOrName(Long id, String name);
使用 #{arg0}
、#{arg1}
.... 指定第几个参数
例如:
SELECT * FROM t_user WHERE id=#{arg0} OR name = #{arg1}
或者 使用 @Param("...")
例如:
UserModel getByIdOrName(@Param("userId") Long id, @Param("userName") String name);
<select id="getByIdOrName" resultType="com.kong.pojo.UserModel">
SELECT * FROM t_user WHERE id=#{userId} OR name = #{userName} LIMIT 1
</select>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架