MyBatis笔记
Mybatis特性
- Mybatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架;
- Mybatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集;
- Mybatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Object 普通Java对象)映射称数据库中的记录;
- Mybatis是一个半自动ORM(Object Relation Mapping)框架;
与其他持久层技术对比
JDBC
- SQL夹杂在Java代码中,耦合度高,导致硬编码内伤;
- 维护不易且实际开发需求中SQL变化,频繁修改的;
- 代码冗长,开发效率低;
Hibernate 和 JPA
- 操作简便,开发效率高;
- 程序中的长难复杂SQL,需要绕过框架;
- 内部自动生产的SQL,不容易做特殊优化;
- 基于全映射的全自动框架,大量字段的POJO进行部分映射时比较困难;
- 反射操作太多,导致数据库性能下降;
MyBatis
- 轻量级,性能出色;
- SQL和Java编码分开,功能边界清晰。Java代码专注业务、SQL语句专注数据;
- 开发效率稍逊与Hibernate,但是完全能够接受;
引入依赖
<dependencies>
<!--Mybatis核心-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!--Mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
</dependencies>
Mybatis核心配置文件
习惯明明为mybatis-config.xml,并无强制要求,整合Spring后,这个配置文件可以省略;
核心配置文件主要用于配置链接数据库的环境以及Mybatis的全局配置信息;
核心配置文件存放位置:src/main/resources目录下;
<?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>
<!--设置链接数据库的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="mappers/*.xml"/>
</mappers>
</configuration>
创建Mybatis映射文件
Mybatis映射文件用于编写SQL,访问以及操作表中的数据;
Mybatis中可以面向接口操作数据,要保证两个一致:
- mapper接口的全类名和映射文件的命名空间(namespace)保持一致;
- mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致;
<?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">
<mapper namespace="com.dou.mybatis.mapper.UserMapper">
<insert id="insertUser" >
insert into user values (null, '豆豆', '123456', 18, '男', '2865295144@qq.com')
</insert>
</mapper>
调用测试
/**
SqlSession默认不自动提交事务,需要手动提交,若需要自动提交事务
可以使用SqlSessionFactory.openSession(true);
*/
@Test
public void test() throws IOException {
//加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取mapper接口对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.insertUser();
//提交事务
sqlSession.commit();
}
Mybatis核心配置文件解析
environments
<!--
environments:配置多个链接数据库的环境
属性:
default:设置默认使用的环境的id
-->
<environments default="development">
<!--
environment:配置某个具体的环境
属性:
id:表示链接数据库的环境的唯一标识,不能重复
-->
<environment id="development">
<!--
transactionManager:设置事务管理方式
属性:
type:"JDBC/MANAGED"
JDBC:表示当前环境中,执行SQL时,使用的是JDBC中原生的事务管理方式,事务的提交或回滚都需要手动处理
MANAGED:被管理,例如Spring
-->
<transactionManager type="JDBC"/>
<!--
dataSource:配置数据源
属性:
type:"POOLED/UNPOOLED/JNDI"设置数据源类型
POOLED:表示使用数据库连接池缓存数据库链接
UNPOOLED:表示不适用数据库链接池
JNDI:表示使用上下文中的数据源
-->
<dataSource type="POOLED">
<!--设置连接数据库的驱动-->
<property name="driver" value="${db.driver}"/>
<!--设置连接数据库的地址-->
<property name="url" value="${db.url}"/>
<!--设置连接数据库的用户名-->
<property name="username" value="${db.username}"/>
<!--设置连接数据库的密码-->
<property name="password" value="${db.password}"/>
</dataSource>
</environment>
</environments>
typeAliases
<!--设置类型别名-->
<typeAliases>
<!--
typeAlias:设置某个类型的别名
属性:
type:设置需要设置别名的类型
alias:设置某个类型的别名,若不设置该属性,那么该属性拥有默认的别名,即类型,且不区分大小写
-->
<typeAlias type="com.dou.mybatis.pojo.User" alias="User"></typeAlias>
<!--以包为单位,将包下所有的类型设置默认的类型别名,即类名,且不区分大小写-->
<package name="com.dou.mybatis.pojo"/>
</typeAliases>
<select id="selectUser" resultType="User">
select * from user
</select>
mappers
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
<!--
以包为单位引入映射文件
1.mapper接口所在的包要和映射文件所在包一致
2.mapper接口和映射文件的名字一致
-->
<package name="com.dou.mybatis.mapper"/>
</mappers>
Mybatis获取参数的两种方式
mybatis获取参数的两种方式:${}和#{};
${}的本质就是字符串拼接,#{}的本质就是占位符赋值;
注意:${}使用字符串拼接的方式拼接SQL,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}使用占位符赋值的方式拼接SQL,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号。
单个字面量类型的参数
若mapper接口中的方法参数为单个的字面量类型;
此时可以使用${}和#{}以任意的名称获取参数的值;
//通过用户名查询信息
User selectUserByName(String userName);
<select id="selectUserByName" resultType="User">
<!--select * from user where username = #{userName};-->
select * from user where username = '${userName}';
</select>
多个字面量类型的参数
若mapper接口中的方法参数为多个时;
此时MyBatis会自动讲这些参数放在一个map集合中,以arg0,arg1…为键,以参数为值;或以param1,param2…为键,以参数为值;因此只需要通过${}和#{}访问map集合中的键就可以获取相对应的值;
//通过用户名密码查询信息
User selectUserByUserNameAndPassWord(String userName, String passWore);
<select id="selectUserByUserNameAndPassWord" resultType="User">
<!--select * from user where username= #{param1} and password = #{param2};-->
select * from user where username= '${arg0}' and password = '${arg1}';
</select>
map集合类型的参数
若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中,只需要通过${}和#{}访问map集合的键就可以获取相对应的值;
User selectUserByMap(Map params);
<select id="selectUserByMap" resultType="User">
select * from user where username = #{userName} and password = #{passWord};
</select>
实体类类型的参数
若mapper接口中的方法参数为实体类对象时
此时可以使用${}和#{},通过访问实体类对象中属性名获取属性值;
int insertUserByUser(User user);
<insert id="insertUserByUser" parameterType="User">
<!--insert into user values (null, #{username}, #{password}, #{age}, #{sex}, #{email});-->
insert into user values(null, '${username}', '${password}', '${age}', '${sex}', '${email}');
</insert>
使用@Param标识参数
可以通过@Param注解标识mapper接口中的方法参数
此时,会将这些参数放在map集合中,以@Param注解的value属性值为键,以参数为值;以param1,param2…为键,以参数为值;只需要通过${}和#{}访问map集合的键就可以获取相对应的值;
User checkLogin(@Param("username") String username, @Param("password") String password);
<select id="checkLogin" resultType="User">
<!--select * from user where username = #{username} and password = #{password};-->
select * from user where username = '${param1}' and password = '${param2}';
</select>
Mybatis各种查询功能
查询一个实体类对象
//通过id查询用户信息
User selectById(@Param("id") int id);
<select id="selectById" resultType="User">
select * from user where id = #{id};
</select>
查询一个List集合
//查询所有用户信息
List<User> selectAll();
<select id="selectAll" resultType="User">
select * from user;
</select>
查询单个数据
//查询总记录数
int selectCount();
<select id="selectCount" resultType="int">
select count(1) from user;
</select>
查询一条数据为map集合
//通过id查询用户信息,结果为一个map集合
Map<String, Object> selectUserByIdToMap(@Param("id") Integer id);
<select id="selectUserByIdToMap" resultType="map">
select * from user where id = #{id};
</select>
查询多条数据为map集合
方式一:
/**
* 查询所有用户信息为map集合
* 将表中数据以map集合的方式查询,一条数据对应一个map;
* 若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取
* @return
*/
List<Map<String, Object>> selectAllToMap1();
<select id="selectAllToMap1" resultType="map">
select * from user;
</select>
方式二:
/**
* 查询所有用户信息为map集合
* 将表中的数据以map集合的方式查询,一条数据对应一个map;
* 若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合
* @return
*/
@MapKey("id")
Map<String, Object> selectAllToMap2();
<select id="selectAllToMap2" resultType="map">
select * from user;
</select>
特殊SQL的执行
模糊查询
//根据用户名模糊查询用户信息
List<User> selectUserByLike(@Param("username") String username);
<select id="selectUserByLike" resultType="User">
<!--select * from user where username like '%${username}%';-->
<!--select * from user where username like concat('%', #{username}, '%');-->
select * from user where username like "%"#{username}"%";
</select>
批量删除
//根据id批量删除
int deleteMore(@Param("ids")String ids);
<delete id="deleteMore">
delete from user where id in (${ids});
</delete>
**注意:**需要使用${}进行获取参数(#{}或拼接’'导致SQL错误)
动态设置表名
//通过传入表名查询数据
List<User> selectUserByTableName(@Param("tableName")String tableName);
<select id="selectUserByTableName" resultType="User">
select * from ${tableName};
</select>
**注意:**需要使用${}进行获取参数(#{}或拼接’'导致SQL错误)
添加功能获取自增的主键
void insertUser(User user);
<!--
useGeneratedKeys:设置当前标签中的SQL使用了自增的主键
keyProperty:将自增的主键的值赋值给传输到映射文件中参数的某个属性
-->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into user values(#{id}, #{username}, #{password}, #{age}, #{sex}, #{email});
</insert>
自定义映射resultMap
处理字段和属性的映射关系
-
为字段起别名,保持和属性名一致;
<select id="selectAll1" resultType="Emp"> select eid, emp_name empName, age, sex, email from t_emp; </select>
-
设置全局配置,将_自动映射为驼峰
<!--设置mybatis全局配置--> <settings> <!--将_自动映射为驼峰--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
-
通过resultMap设置自定义的映射关系
<!-- resultMap:设置自定义映射关系 id:唯一标识,不能重复 type:设置映射关系中的实体类类型 字标签: id:设置主键的映射关系 result:设置普通字段的映射关系 属性: property:设置映射关系中的属性名,必须是type属性所设置的实体类类型中的属性名 column:设置映射关系中的字段名,必须是SQL语句查询出的字段名 --> <resultMap id="empResultMap" type="Emp"> <id property="eid" column="eid"/> <result property="empName" column="emp_name"/> <result property="age" column="age"/> <result property="sex" column="sex"/> <result property="email" column="email"/> </resultMap> <select id="selectAll2" resultMap="empResultMap"> select * from t_emp; </select>
多对一映射处理
-
级联属性赋值
<!--处理多对一映射关系方式一:级联属性赋值--> <resultMap id="empAndDeptResultMapOne" type="Emp"> <id property="eid" column="eid"/> <result property="empName" column="emp_name"/> <result property="age" column="age"/> <result property="sex" column="sex"/> <result property="email" column="email"/> <result property="dept.did" column="did"/> <result property="dept.deptName" column="dept_name"/> </resultMap> <select id="selectEmpAndDept" resultMap="empAndDeptResultMapOne"> select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid = #{eid}; </select>
-
association
<!--处理多对一映射关系方式二:association--> <resultMap id="empAndDeptResultMapTwo" type="Emp"> <id property="eid" column="eid"/> <result property="empName" column="emp_name"/> <result property="age" column="age"/> <result property="sex" column="sex"/> <result property="email" column="email"/> <!-- association:处理多对一的映射关系 property:需要处理多对一映射关系的属性名 javaType:该属性的类型 --> <association property="dept" javaType="Dept"> <id property="did" column="did"/> <result property="deptName" column="dept_name"/> </association> </resultMap> <select id="selectEmpAndDept" resultMap="empAndDeptResultMapTwo"> select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid = #{eid}; </select>
-
分步查询
<!--处理多对一映射关系三:分步查询--> <resultMap id="empAndDeptStepResultMap" type="Emp"> <id property="eid" column="eid"/> <result property="empName" column="emp_name"/> <result property="age" column="age"/> <result property="sex" column="sex"/> <result property="email" column="email"/> <!-- select:设置分步查询的SQL的唯一标识(namespace.SQLId或mapper接口的全类名.方法名) column:设置分步查询的条件 fetchType:当开启了全局的延迟加载之后,可通过此属性手动控制延迟加载的效果 fetchType="lazy|eager":lazy表示延迟加载,eager表示立刻加载 --> <association property="dept" fetchType="lazy" select="com.dou.mybatis.mapper.DeptMapper.selectById" column="did"/> </resultMap> <select id="selectEmpAndDeptStep" resultMap="empAndDeptStepResultMap"> select * from t_emp where eid = #{eid}; </select>
<select id="selectById" resultType="Dept"> select * from t_dept where did = #{did}; </select>
一对多映射处理
-
collection
<resultMap id="deptAndEmpResultMap" type="Dept"> <id property="did" column="did"/> <result property="deptName" column="dept_name"/> <!-- collection:处理一对多的映射关系 ofType:表示该属性所对应的集合中存储数据的类型 --> <collection property="empList" ofType="Emp"> <id property="eid" column="eid"/> <result property="empName" column="emp_name"/> <result property="age" column="age"/> <result property="sex" column="sex"/> <result property="email" column="email"/> </collection> </resultMap> <select id="selectDeptAndEmp" resultMap="deptAndEmpResultMap"> select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}; </select>
-
分步查询
<resultMap id="deptAndEmpStepResultMap" type="Dept"> <id property="did" column="did"/> <result property="deptName" column="dept_name"/> <collection property="empList" select="com.dou.mybatis.mapper.EmpMapper.selectEmpByDid" column="did" fetchType="lazy"/> </resultMap> <select id="selectDeptAndEmpStep" resultMap="deptAndEmpStepResultMap"> select * from t_dept where did = #{did}; </select>
<select id="selectEmpByDid" resultType="Emp"> select * from t_emp where did = #{did}; </select>
分步查询
分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息;
lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载,默认为false;
aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载,默认为false;
此时就可以实现按需加载,获取的数据是什么,就只会执行相应的SQL。此时可通过association和collection中的fetchType属性设置当前分步查询是否使用延迟加载,fetchType=“lazy(延迟加载)|eager(立即加载)”;
动态SQL
Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题。
if
if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行;
<select id="selectEmpByConditionIf" resultType="Emp">
select * from t_emp where 1=1
<if test="empName != null and empName != ''">
and emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
<if test="email != null and email!= ''">
and email = #{email}
</if>
</select>
where
当where标签中有内容时,会自动生成where关键字,并且将内容前多余的and或者or去掉;
当where标签中没有内容时,此时where标签没有任何效果
**注意:**where标签不能将其中内容后面多余的and或or去掉
<select id="selectEmpByConditionWhere" resultType="Emp">
select * from t_emp
<where>
<if test="empName != null and empName != ''">
and emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
<if test="email != null and email!= ''">
and email = #{email}
</if>
</where>
</select>
trim
若标签中有内容时:
prefix/suffix:将trim标签中内容前面或后面添加指定内容;
prefixOverrides/suffixOverrides:将trim标签中内容前面或后面去掉指定内容;
若标签中没有内容时,trim标签也没有任何效果;
<select id="selectEmpByConditionTrim" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and|or">
<if test="empName != null and empName != ''">
emp_name = #{empName} and
</if>
<if test="age != null and age != ''">
age = #{age} and
</if>
<if test="sex != null and sex != ''">
sex = #{sex} and
</if>
<if test="email != null and email!= ''">
email = #{email} or
</if>
</trim>
</select>
choose、when、otherwise
**注意:**when至少要有一个,otherwise最多只能有一个
<select id="selectEmpByConditionChooseWhenOtherwise" resultType="Emp">
select * from t_emp where
<choose>
<when test="empName != null and empName != ''">
emp_name = #{empName}
</when>
<when test="age != null and age != ''">
age = #{age}
</when>
<when test="sex != null and sex != ''">
sex = #{sex}
</when>
<when test="email != null and email != ''">
email = #{email}
</when>
<otherwise>
eid = 1
</otherwise>
</choose>
</select>
foreach
collection:设置需要循环的数组或集合;
item:表示数组或集合中的每一个数据;
separator:循环体之间的分隔符;
open:foreach标签所循环的所有内容的开始符;
close:foreach标签所循环的所有内容的结束符
批量删除
<delete id="deleteMoreByArray1">
delete from t_emp where eid in
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
<delete id="deleteMoreByArray2">
delete from t_emp where
<foreach collection="eids" item="eid" separator="or">
eid = #{eid}
</foreach>
</delete>
批量添加
<insert id="insertMoreByList">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null, #{emp.empName}, #{emp.age}, #{emp.sex}, #{emp.email}, null)
</foreach>
</insert>
sql
设置SQL片段:XXX
引用SQL片段:
<sql id="empColumns">
eid,emp_name,age,sex,email
</sql>
<select id="selectEmpByid" resultType="Emp">
select <include refid="empColumns"/> from t_emp where eid = #{eid};
</select>
Mybatis缓存
mybatis的一级缓存
一级缓存是SQLSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问。
使一级缓存失效的四种情况:
- 不同的SqlSession对应不同的一级缓存;
- 同一个SqlSession但是查询条件不同;
- 同一个SqlSession两次查询期间执行了任何一次增删改操作;
- 同一个SqlSession两次查询期间手动清空了缓存;
mybatis的二级缓存
二级缓存是SQLSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取;
二级缓存开启的条件:
- 在核心配置文件中,设置全局配置属性cacheEnabled=“true”,默认为true,不需要设置;
- 在映射文件中设置标签
- 二级缓存必须在SqlSession关闭或提交之后有效;
- 查询的数据所转化的实体类类型必须实现序列化接口;
使二级缓存失效的情况
两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效。
二级缓存相关配置
在mapper配置文件中添加的cache标签可以设置一些属性:
-
eviction属性:缓存回收策略
LRU(Least Recently Used)-最近最少使用的:移除最长时间不被使用的对象;
FIFO(First in First out)-先进先出:按对象进入缓存的顺序来移除它们;
SOFT:-软引用:移除基于垃圾回收期状态和软引用规则的对象;
WEAK:-弱引用:更积极的移除基于垃圾收集器状态和弱引用规则的对象;
默认是LRU
-
flushInterval属性:刷新间隔,单位毫秒;
默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新;
-
size属性:引用数目,正整数
代表缓存最多可以存储多少个对象,太大容易导致内存溢出;
-
readOnly属性:只读,true/false
true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不会被修改。这提供了很重要的性能优势。
false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。
mybatis缓存查询的顺序
- 先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用;
- 如果二级缓存中没有命中,再查询一级缓存;
- 如果一级缓存也没有命中,则查询数据库;
- SqlSession关闭之后,一级缓存中的数据会写入二级缓存;
分页插件
分页插件使用步骤
-
添加依赖
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.0</version> </dependency>
-
配置分页插件
在Mybatis的核心配置文件中配置插件
<plugins> <!--设置分页插件--> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins>
分页插件的使用
-
在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能
pageNum:当前页的页码
pageSize:每页显示的条数
-
在查询获取List集合之后,使用PageInfo pageInfo = new PageInfo<>(List list, int navigatePages)获取分页相关数据
list:分页之后的数据
navigatePages:导航分页的页码数
-
常用数据
字段 含义 pageNum 当前页的页码 pageSize 每页显示的条数 size 当前页显示的真实条数 total 总记录数 pages 总页数 prePage 上一页的页码 nextPage 下一页的页码 isFirstPage/isLastPage 是否为第一页/最后一页 hasPreviousPage/hasNextPage 是否存在上一页/下一页 navigatePages 导航分页的页码数 navigatepageNums 导航分页的页码
@Test
public void test(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
PageHelper.startPage(1,2);
List<User> users = mapper.selectAll();
users.forEach(System.out::println);
PageInfo pageInfo = new PageInfo(users, 3);
System.out.println(pageInfo);
}