Mybatis 高阶2021年3月30日 2021年4月1日
:::success
插入test文件
:::
作业作业.txt Day08Mybatis(01) 潘晨.zip 老师链接
4反向代理
我们在使用Mybatis的时候,手动指定了sq语句的地址,这样做其实是很不方便的。因为我们的java编程,其实是面向接口编程。也就是我们在使用Mybatis的时候,应该去调用接口,而不是去直接写死SQL语句的地址,然后去调用。
条件
我们的mapper.xml的namespace和我们的Mapper.java的全限定名称 保持一致 我们Mapper.xml里面的<insert>``<select>``<update>``<delete> 这些标签的id和我们接口里面方法 的名称保持一致 我们接口方法的参数和返回值的类型 要和我们Mapper.xml 里面的resultType以及ParamterType保持一致
代理对象如何使用UserMapper mapper = sqlSession . getMapper ( UserMapper . class );
那我们就可以直接去调用UserMapper这个接口里面的接口了
5输入映射
定义:
输入映射,是在映射文件中通过 parameterType 指定输入参数的类型,类型可以是简单类型、 hashmap 、 pojo 的包装类型。假设现在有个比较复杂的查询需求:完成用户信息的综合查询,需要传入查询条件很复杂(可能包括用户信息、其它信息,比如商品、订单的),那么我们单纯的传入一个 User 就不行了,所以首先我们得根据查询条件,自定义一个新的 pojo ,在这个 pojo 中包含所有的查询条件
步骤复制新工程—-ch03-mybatis-param.zip
:::tips
复制工程步骤
复制粘贴文件 删除.idea 和???文件 修改pom.xml文件内的artifactId内容 projectstructure导入pom.xml文件
:::
5.1@param注解—-传参 这个注解就是给我们的传参来起名字的一个注解,那么我们如果加了这个注解以后,就需要取值的时候,使用这个注解里面的值
:::warning
@param(“id”) 那么#{}里面必须写id 不可以乱写
:::
5.2 简单参数
一个简单的参数—-省略or注解
简单类型参数:Mybatis定义了我们的基本类型,以及字符串类型都是简单类型的参数,那么这个时候就可以在我们mapper.xml标签中省略 parameterType= int 这样的传参
:::info
Mybatis内置别名类型就是简单类型 java中包括: 基本类型+java.long.String 简单类型传参 , 入参(=parameterType)可以省略
:::
:::warning
一个参数#{}里面
:::
多个简单的参数—-一定用@param注意一下,我们传多个参数的时候,一定要使用@Param 注解,不然会找不到对应的参数
:::tips
binding 绑定异常
:::
5.4 对象传值通过对象来传值,我们如何去在UserMapper.xml文件中去取值呢?
无@param注解———-#{成员变量的名字}// 插入用户
Integer insertUser(User user);
有@param注解—-#{@Param注解里面的值.成员变量的名字}// 插入用户
Integer insertUser(User user);
5.5map传值[不推荐]
无@param注解—- #{key}
@param注解 假如我们在传值的Map前面,加了@Param注解,那么这种取值的方式还ok吗? 这种方式不ok了,我们应该这么取值 #{map.key} 来取值 在传值加中param, 方式一不可用 #{map.id} #{map.username}
mapper接口
mapper.xml文件 result里面写单个bean类型—-输出传出的是list
思考:Map传值好嘛:
不好, 对象比map好
使用Map传值不好,因为Map对象里面没有定义我们应该使用什么key,那么假如是你写了一个接口,别人来用你的接口的时候,他看见了是通过Map传值,那么他怎多知道去给这个Map里面应该封装什么样的Key呢?|
map本身没有id username是由调用者放入,如果写错就取不到了
我们不推荐使用Map来进行传值,任何场景都不推荐。
例如我们的Mybatis的map传值、例如我们的前后端交互使用Map传值,例如我们去使用消息队列的时候也不推荐使用Map传值。
:::tips
任何场景都不推荐使用map传值, 进行数据交互
:::
5.6~~位置传值[不推荐] ~~#{param1}mapper接口: mapper.xml文件 #{param1} == #{arg0} //注意两个标记起始点一个是1 一个是0
不推荐原因:
容易出错
不方便阅读
代码维护性变差
代码伸缩性变差
-
5.7 #与$符号对比[面试可能问]
运行日志
二者区别
#{}
${}
原理
使用的预编译(preparestatement)
使用字符串拼接
使用 场景
一般情景
传递表名[#取不到] 传递列名[#可以取到,但是还是推荐$]
弊端
会出现数据库注入问题
$取值推荐情形${} 去取值这种方式,有他的用途
当我们给Mybatis的sql语句传递表名的时候,我们必须通过${}来取值 我们需要传递表名的这种方式有什么使用场景呢? 我们之前给大家讲了,我们Mysql单表数据是性能上限的,假如我们的单表数据太多了,那么这个时候就需要分表,那么需要分表的话,就相当于很多数据存到了不同的表里面,但是这些表的结构一样,只是名字不一样,那么这个时候我们就可以把表名在我们的代码里面先查出来,然后把表名作为条件传给SQL语句 传递列名的时候,也是一样的(order by ${}, group by ${}) 我们也是一般通过${} 来取值的,因为我们通过${}来取值,效率更高,并且基本上在这种场景下没有sql注入的风险 而且使用#{}去取值的时候,我们发现查询出来的结果不对。
为什么通过#{tableName)取值的时候会报错呢?
因为我们的#取值的的候,底层是prepareStatement,这个prePareStatement会对我们的sq语句进行预编译,假如你的表名缺失,那么编译就会报错。
传递表名的使用场景
分表分库
我们之前给大家讲了,我们Mysql单表数据是性能上限的,假如我们的单表数据太多了,那么这个时候就需要分表,那么需要分表的话,就相当于很多数据存到了不同的表里面,但是这些表的结构一样,只是名字不一样,那么这个时候我们就可以把表名在我们的代码里面先查出来,然后把表名作为条件传给SQL语句
17点14分
传递列名的使用场景
order by
group by
我们也是一般通过${}来取值的,甲为我们通过${}来取值,效率更高,并且基本上没有sq注入的风险。
列名被orderby 一般只是查询 没有输入参数的风险 比较适合用 $
使用预编译要通信两次$只需要通信一次, 因此效率更高
6输出映射ch04-mybatis-output-mapping.zip
定义
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。如果查询出来的列名和pojo中的属性名全部不一致,没有创建pojo对象。
只要查询出来的列名和pojo中的属性有一个一致,就会创建pojo对象。
6.1 简单类型
简单类型= java基本类型+string
注意,
我们的标签的是可以省略的,
但是或者是不能省略。select 返回值不可以省略resultType/ resultMap写一个
resultType可以使用别名
也就是说,我们的sql语句,假如是一个查询类型的话,那么他的参数可以省略,但是返回值类型不能省略
单个简单类型mapper.xml
<!-- resultType不能省略, 可以使用别名 -->
<select id="selectUserAgeById" resultType="integer">
select age from user2 where id = #{adfnA}
</select>
mapper
// 输出映射 简单类型(Java 中的基本类型和String)
Integer selectUserAgeById(Integer id);
通常配置 count、avg、max等聚合函数来使用
简单类型的集合mapper
// 简单类型的List
// 假如我们需要获取的是一个字符串类型的数组,只需要在这个地方把返回值类型修改为String[] 即可,我们的mapper.xml不用去更改
//
List<String> selectUserNameList();
mapper.xml
<select id="selectUserNameList" resultType="string">
select username from user2
</select>
:::tips
:::
通常配置count、avg、max等聚合函数来使用
6.2 pojo对象和pojo对象列表
对象返回值类型是对象是,我们需要保证成员变量(setter方法)与数据库字段保持一致mapper.xml
<select id="selectUserById" resultType="com.cskaoyan.dto.User">
select * from user2 where id = #{id}
</select>
mapper
User selectUserById(@Param("id") Integer id);
问题: 字段对应不上的时候,我们就封装不进去了,那么有没有办法能够解决这种问题呢?解决方法
①给列起别名, 让javaBean保持一致 (投机去交)
<select id="selectUserById2" resultype="com. cskaoyan. dto. Uservo">
select id as id, username as name, password as passwd, age as age from user2 where id=#{ id}
</select>
②resultmap
2021年3月31日
对象列表其实也就是一个对象集合
6.3 ResultMap—-可以映射—-更重要的时进行多表查询我们可以取把我们查询出来的结果封装到一个特地的JavaBean里面,打破数据库列名和我们JavaBean的成员变量名必须一致的这种限制
单个Bean假如出现数据库名字和我们的JavaBean对应不上的时候,那么我们可以通过resultMap来解决这个问题
<!--
resultMap : 根节点
id: 这个resultMap的名字
type: 这个resultMap映射的JavaBean
id: 数据库中主键的映射(是为了提高效率,把他换成result也可以)
column: 数据库中的字段名
property: 成员变量名
javaType: Java语言中的类型
jdbcType: 数据库中的类型,参考#{org.apache.ibatis.type.JdbcType}
result: 普通列的映射
注意: javaType 和jdbcType一般可以省略
-->
<resultMap id="userVOMap" type="com.cskaoyan.dto.UserVO">
<!-- JdbcType JavaType 可以省略-->
<id property="id" column="id" />
<result column="username" property="name"/>
<result column="password" property="passwd"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectUserById3" parameterType="int" resultMap="userVOMap">
select * from user2 where id = #{id}
</select>
对象列表mapper
// resultMap
List<UserVO> selectUserVOList();
mapper.xml
<resultMap id="userVOMap" type="com.cskaoyan.dto.UserVO">
<!-- JdbcType JavaType 可以省略-->
<id property="id" column="id" />
<result column="username" property="name"/>
<result column="password" property="passwd"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectUserVOList" resultMap="userVOMap">
select * from user2
</select>
8 动态SQL
8.1 wheremapper.xml
<select id="selectUserByIdAndUserName" resultType="com.cskaoyan.dto.User">
select * from user2
<where>
id = #{id}
and username = #{username}
</where>
</select>
where标签三个作用
sql语句中拼接where字符sql语句中去除跟着的and或者orwhere 标签里面没有内容,不会拼接where
8.2 if这个标签可以帮助我们动态的去根据我们传入的条件,去拼接我们的sql语句
test 里面是一个OGNL表达式,结果是Boolean类型
<if test="这里是我们需要判别的条件">
这里是我们需要拼接的SQL
</if>
两个例子
mapper
// 现在有一个需求,我们传入一个数值,假如这个数值比20大,那么我们就查询出所有的年龄比20大的用户
// 假如我们传入的数值比20小,那么我们就查询出所有年龄比20小的用户
List<User> selectUserLisyByAge(@Param("age") Integer age);
// if语句的第二个使用场景
// 根据我们传入的条件去匹配用户
List<User> selectUserBySelf(@Param("user") User user);
mapper.xml
<!--
1. if test="判别式"
上面的判别式是OGNL表达式,其实就是一个特殊的取值的表达式,这个表达式的结果必须是一个boolean类型的值
这个里面有几个需要注意的地方,关于大于和小于的写法要写成他规定的字符
不等于 a != b
不为空 != null
大于 gt (greater than)
小于 lt (less than)
大于等于 gte(greater than equals)
小于等于 lte(less than equals)
2. 关于XML文本里面的转义字符 (特殊字符)
& &
> >
< <
>= >=
<= <=
-->
<select id="selectUserLisyByAge" resultType="com.cskaoyan.dto.User">
select * from user2
<where>
<if test="age gt 20">
age > 20
</if>
<if test="age lte 20">
age <= 20
</if>
</where>
</select>
<select id="selectUserBySelf" resultType="com.cskaoyan.dto.User">
select * from user2
<where>
<if test="user.id != null">
or id = #{user.id}
</if>
<if test="user.username != null">
and username = #{user.username}
</if>
<if test="user.password != null">
and password = #{user.password}
</if>
<if test="user.age != null">
and age = #{user.age}
</if>
</where>
</select>
8.3 choose when表示开启判断
相当于if
相当于else
<select id="selectUserLisyByAge2" resultType="com.cskaoyan.dto.User">
select * from user2
<where>
<choose>
<when test="age gt 20">
age > 20
</when>
<otherwise>
age <= 20
</otherwise>
</choose>
</where>
</select>
8.4 trimtrim这个标签,可以帮助我们动态的去拼接一些字符或者是去除一些字符
<!--
trim 翻译过来是修剪的意思,作用是可以帮助我们动态的去拼接或者修剪我们的sql语句
标签里面有自己参数可以去设置
prefix 表示在头部拼接一个sql字段
suffix 表示在尾部拼接一个sql字段
prefixoverrides 表示去除在头部的指定的字符
suffixoverrides 表示去除在尾部指定的字符
-->
<update id="updateUserBySelf" parameterType="com.cskaoyan.dto.User">
<!--update user2 set username = #{user.username},-->
<!--password = #{user.password},-->
<!--age = #{user.age}-->
<!--where id = #{user.id}-->
update user2
<trim prefix="set" suffixOverrides=",">
<if test="user.username != null">
username = #{user.username},
</if>
<if test="user.password != null">
password = #{user.password},
</if>
<if test="user.age != null">
age = #{user.age},
</if>
</trim>
<where>
id = #{user.id}
</where>
</update>
8.5 set这个标签其实和我们的trim有点类似,等同于
<!-- update user2 SET username = ? WHERE id = ? -->
<update id="updateUserByIdWithSet">
update user2
<set>
<if test="user.username != null">
username = #{user.username},
</if>
<if test="user.password != null">
password = #{user.password},
</if>
<if test="user.age != null">
age = #{user.age},
</if>
</set>
<where>
id = #{user.id}
</where>
</update>
8.6 sql-includesql其实是把反复出现的一些sql片段抽离出来,实现复用
说明:
我们sql-include标签可以帮助我们反复利用一个sql片段,但是这样会导致我们的sql的阅读性变差,所以一般我们不会把一些含有关键字的sql片段给抽离出来,例如上面的<base_select> 这种方式的抽离其实很少使用。一般我们呢只会把一些基本的列抽离出来,这样既可以做到复用,又可以不损伤sql的可读性
8.7 foreachforeach这个标签,常用的场景有两个
批量插入mapper
```java
// 插入一个list
Integer insertUserList(@Param(“userList”) List userList);
Integer insertUserList2(List userList);
// 批量插入数组
Integer insertUserList3(User[] userarr);
Integer insertUserList4(@Param(“userarr”) User[] userarr);
- mapper.xml
```xml
<!--
collection: 这个是传进来的集合的名字 假如有@Param注解,那么就是注解的值,假如没有就是list/array
item: 表示集合中单个bean的名字
separator: 这个是表示我们的集合中的元素以什么符号分隔开
index: 表示下标
open: 其实是表示在我们这个循环拼接而成的sql语句之前加上一个特定的字符
close: 其实就是在我们这个循环拼接而成的sql语句的后面加上一个特定的字符
-->
<!-- insert into user2 values start (?, ?, ?, ?) , (?, ?, ?, ?) end -->
<insert id="insertUserList" parameterType="com.cskaoyan.dto.User">
insert into user2 values
<foreach collection="userList" item="user" separator="," index="index">
(#{user.id}, #{user.username}, #{user.password}, #{user.age})
</foreach>
</insert>
<insert id="insertUserList2" parameterType="com.cskaoyan.dto.User">
insert into user2 values
<foreach collection="list" item="user" separator="," index="index">
(#{user.id}, #{user.username}, #{user.password}, #{user.age})
</foreach>
</insert>
<insert id="insertUserList3" parameterType="com.cskaoyan.dto.User">
insert into user2 values
<foreach collection="array" item="user" separator="," index="index">
(#{user.id}, #{user.username}, #{user.password}, #{user.age})
</foreach>
</insert>
<insert id="insertUserList4" parameterType="com.cskaoyan.dto.User">
insert into user2 values
<foreach collection="userarr" item="user" separator="," index="index">
(#{user.id}, #{user.username}, #{user.password}, #{user.age})
</foreach>
</insert>
通过in查找mapper
// 通过一个idList来查找userList
List<User> selectUserListByIdList(@Param("idList") List<Integer> idList);
mapper.xml
<select id="selectUserListByIdList" resultType="com.cskaoyan.dto.User">
select <include refid="base_column"/>
from user2
<where>
id in
<foreach collection="idList" separator="," item="id" open="(" close=")">
#{id}
</foreach>
</where>
</select>
8.8 selectKey 这个标签其实是在你执行的真正要执行的sql语句前面或者是后面执行额外的一条sql语句
通常他的作用有:
例如我们的主键是自增的,那么我们在插入数据库以后 数据库会帮我们生成一条主键,这个时候我想要获得这条生成的主键,是不是得先插入,在查询,那么针对这种场景,我们就可以使用 标签
<!--
order : 表示我们执行这个标签里面的sql语句的先后顺序
AFTER 表示在后面执行
BEFORE 表示在前面执行
keyProperty: 表示我们需要获取的数据封装到哪里
keyColumn: 表示你需要获取的是哪一列的数据
resultType: 这个是表示你获取到的返回值的类型
-->
<insert id="insertUser" parameterType="com.cskaoyan.dto.User">
<selectKey order="AFTER" keyProperty="user.id" keyColumn="id" resultType="integer">
select LAST_INSERT_ID()
</selectKey>
insert into user2 values (#{user.id}, #{user.username}, #{user.password}, #{user.age})
</insert>
8.9 useGeneratedKeys这个是一个标签中的属性,其实就是可以帮助我们去取到生成的主键的值(这个是比较常用的)
<!--
useGeneratedKeys: 表示开启自增主键的功能
keyProperty: 表示把值映射到哪里去
-->
9 多表查询
9.1 一对一建立一对一的模型关系,例如用户和用户详情对象之间的关联
连接查询执行了一条sql语句
mapper
// 通过用户去查询用户以及用户详情
User selectUserWithDetailById(@Param("id") Integer id);
mapper.xml
<!--
在我们的多表之间的关系是一对一的时候,那么使用<association> 这个标签,
javaType : 对应的就是我们这个bean里面成员变量的类型
property: 这个其实就是和我们JavaBean中的成员变量的名字保持一致
-->
<resultMap id="userMap" type="com.cskaoyan.dto.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="age" property="age"/>
<association property="userDetail" javaType="com.cskaoyan.dto.UserDetail">
<result column="did" property="id"/>
<result column="pic" property="pic"/>
<result column="sign" property="sign"/>
<result column="userid" property="userId"/>
</association>
</resultMap>
<!--这个是我们的查询入口
在这里,我们给我们需要的一些列起了别名,目的是为了和JavaBean中的成员变量去做更好的映射
-->
<select id="selectUserWithDetailById" resultMap="userMap">
SELECT
u.id as id,
u.username as username,
u.password as password,
u.age as age,
d.id as did,
d.pic as pic,
d.sign as sign,
d.user_id as userid
FROM
user2 AS u,
user_detail AS d
WHERE
u.id = d.user_id
and u.id = #{id}
</select>
分次查询通过日志发现,执行了多条sql语句
<!--分次查询 -->
<resultMap id="userCountMap" type="com.cskaoyan.dto.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="age" property="age"/>
<!--通过第二次查询去映射到我们的userDetail-->
<association property="userDetail" javaType="com.cskaoyan.dto.UserDetail"
select="selectUserDetailByUserId" column="id"/>
</resultMap>
<select id="selectUserWithDetailById2" resultMap="userCountMap">
select id,username,password,age from user2 where id = #{id}
</select>
<select id="selectUserDetailByUserId" resultType="com.cskaoyan.dto.UserDetail">
select
id as id,
user_id as userId,
pic as pic,
sign as sign
from user_detail
where user_id = #{xxx}
</select>
9.2 一对多
建立模型 ————- 班级和学生建表
建立JavaBean
连接查询mapper
// 通过班级的名字去查询班级信息以及班级的学生信息
Clazz selectClazzWithStudentsByName(@Param("name") String name);
mapper.xml
<resultMap id="classMap" type="com.cskaoyan.dto.Clazz">
<id column="id" property="id"/>
<result column="name" property="name"/>
<!--
需要注意的几个地方
1. collection : 表示我们封装的成员变量是一个集合 假如是单个bean,用association
2. 集合的类型,我们写集合里面元素的类型 并且用ofType ,假如是单个bean,我们用javaType
-->
<collection property="studentList" ofType="com.cskaoyan.dto.Student">
<result column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="classid" property="classId"/>
</collection>
</resultMap>
<select id="selectClazzWithStudentsByName" resultMap="classMap">
SELECT
c.id as id,
c.name as name,
s.id as sid,
s.name as sname,
s.class_id as classid
FROM
clazz AS c
LEFT JOIN student AS s ON c.id = s.class_id
where c.`name` = #{name}
</select>
分次查询
9.3 多对多多对多其实对于Mybatis来说其实就是一对多
模型 学生和课程建表、建立JavaBean
连接查询
mapper
// 根据学生姓名去查询学生以及他的选课信息
Student selectStudentWithCoursesByName(@Param("name") String name);
mapper.xml
```xml
SELECT
s.id AS id,
s.NAME AS name,
s.age AS age,
c.id AS cid,
c.name AS cname
FROM
student AS s
LEFT JOIN s_c AS sc ON s.id = sc.sid
LEFT JOIN course AS c ON c.id = sc.cid
WHERE
s.NAME = #{name}
<a name="YWfG7"></a>
#### 分次查询xml
select id,name,age from student where name = #{name}
SELECT
c.id AS id,
c.NAME AS name
FROM
s_c as sc
LEFT JOIN course as c ON sc.cid = c.id
WHERE
sc.sid = #{id}
总结一下:分次查询和连接查询各有什么优缺点呢?
- 目前而言,看起来时连接查询更加简单一点,因为连接查询就是两个步骤
1. 写sql语句
1. 封装对象
而我们的分次查询,要多些一条sql,还要去把两次sql关联起来<br />从效率上来说,也可能是连接查询可能更快一点(但是不是绝对的)<br />在什么情况我们的分次查询比连接查询要好一点呢?<br />假如我们现在连接的两个表或者是多个表都数据量很大,那么去做连接查询的时候就可能会很慢,因为连接查询产生的中间表可能会数据量爆炸
- 分次查询也给我们提供了一个提高效率的办法<br />**懒加载**
<a name="CJ1Fo"></a>
## 10 懒加载
懒加载其实就是延迟加载。什么意思呢?
在我们使用分次查询的时候,那么我们第一次查询会给我们的JavaBean里面去封装一些字段,第二次查询又会给JavaBean里面封装一个字段(假如叫做字段A),当我们开启懒加载的时候,只要我们不使用到这个JavaBean里面的字段A,那么就不会去执行第二次查询,当我们用到这个字段A的时候,才会去执行第二次查询。
如何开启呢?
- 全局开关
```xml
<!--全局懒加载开关-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--通过第二次查询去映射到我/们的userDetail-->
<association property="userDetail" javaType="com.cskaoyan.dto.UserDetail"
select="selectUserDetailByUserId"column="id" fetchType="eager"/>
fetchType = lazy 这个表示开启懒加载fetchType=eager 这个表示关闭懒加载
我们首先会以局部开关为准( 即使全局开关没有开启,也会以局部开关为准 ),假如没有配置局部开关,那么会以全局开关为准
问题: 懒加载有什么作用呢?
提高效率,减轻内存的压力。
11 缓存Mybatis为了提高我们的查询效率,增加了缓存功能,可以帮助我们提高Mybatis的性能
Mybatis的缓存一级缓存和二级缓存
一级缓存什么叫缓存?缓存的目的是什么呢?
缓存就是相当于在内存中给我们提供了一个数据的备份,缓存的目的是帮助我们提高查询效率
说明:Mybatis的以及缓存是默认开启的
一级缓存是我们Mybatis给我们提供的一个会话级别的缓存,是基于同一个会话的。是SqlSession级别的
会话这个概念在EE里面会重点学习(一天),什么叫一次会话呢?
其实你可以理解为打电话,在打电话的过程中,你可以理解为是一次会话。假如关闭了电话,这个时候会话就结束了。
假如我们使用的是Socket,那么这种就叫做长连接,只要我们不主动断开,他就会一直保持会话
假如我们使用的是HTTP,这个协议每次建立连接都需要经过3次握手,每一次去传输一个新的信息都需要重新建立连接,传输完成之后关闭连接,类似于这种网络协议就叫做短连接。所以在HTTP1.1之后他加入了一个属性,keepAlive这个属性,其实就是一直让他去保持连接。
在Mybatis里面什么叫一次会话呢?其实就是同一个sqlSession,只要你是基于同一个sqlSession,那么默认就会去查询一级缓存。
问题:一级缓存什么时候失效呢?
会话关闭或者会话提交 传入的条件参数不一致的时候 在我们执行完增、删、改之后会失效
public class CacheTest {
static SqlSession sqlSession;
static UserMapper userMapper;
static ClazzMapper clazzMapper;
static StudentMapper studentMapper;
static SqlSessionFactory sqlSessionFactory;
@BeforeClass
public static void init() throws IOException {
// 需要去加载Mybatis,然后启动Mybatis,然后执行sql,获取结果
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 第二步
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 创建一个SqlSessionFactory
sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
// 创建Sqlsession
sqlSession = sqlSessionFactory.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
clazzMapper = sqlSession.getMapper(ClazzMapper.class);
studentMapper = sqlSession.getMapper(StudentMapper.class);
}
// @AfterClass
// public static void destory(){
//
// sqlSession.commit();
// sqlSession.close();
//
// }
// 一级缓存第一种情况,基于同一个 userMapper
@Test
public void testSelectUserById(){
User user1 = userMapper.selectUserById(10); // 查询数据库,并且把结果放入一级缓存
User user2 = userMapper.selectUserById(10); // 查询一级缓存
User user3 = userMapper.selectUserById(10); // 查询一级缓存
User user4 = userMapper.selectUserById(10); // 查询一级缓存
System.out.println(user1);
System.out.println(user2);
System.out.println(user3);
System.out.println(user4);
sqlSession.commit(); // 清空缓存
User user5 = userMapper.selectUserById(10);
sqlSession.close();
}
// 一级缓存第二种情况, 不同的userMapper,但是是同一个sqlSession
@Test
public void testSelectUserById2(){
UserMapper userMapper1 = sqlSession.getMapper(UserMapper.class);
UserMapper userMapper2 = sqlSession.getMapper(UserMapper.class);
UserMapper userMapper3 = sqlSession.getMapper(UserMapper.class);
UserMapper userMapper4 = sqlSession.getMapper(UserMapper.class);
User user1 = userMapper1.selectUserById(10); // 放入一级缓存
User user2 = userMapper2.selectUserById(10); // 查询一级缓存
User user3 = userMapper3.selectUserById(10); // 查询一级缓存
User user4 = userMapper4.selectUserById(10); // 查询一级缓存
System.out.println(user1);
System.out.println(user2);
System.out.println(user3);
System.out.println(user4);
System.out.println("查询UserId为11......");
User user = userMapper4.selectUserById(11);
}
// 不同的sqlSession,不会走一级缓存
@Test
public void testSelectUserById3(){
SqlSession sqlSession1 = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
SqlSession sqlSession3 = sqlSessionFactory.openSession();
SqlSession sqlSession4 = sqlSessionFactory.openSession();
UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);
UserMapper userMapper4 = sqlSession4.getMapper(UserMapper.class);
User user1 = userMapper1.selectUserById(10);
User user2 = userMapper2.selectUserById(10);
User user3 = userMapper3.selectUserById(10);
User user4 = userMapper4.selectUserById(10);
System.out.println(user1);
System.out.println(user2);
System.out.println(user3);
System.out.println(user4);
}
// 模拟插入数据一级缓存失效的情况
@Test
public void testSelectUserById4(){
User user1 = userMapper.selectUserById(10); // 查询数据库,并且把结果放入一级缓存
User user2 = userMapper.selectUserById(10); // 查询一级缓存
// 插入数据
Integer affectedRows = inserUser(); // 插入数据会情况一级缓存
if (affectedRows > 0) {
System.out.println("插入数据成功....");
}else {
return;
}
User user3 = userMapper.selectUserById(10); // 查询数据库并放入一级缓存
User user4 = userMapper.selectUserById(10); // 查询一级缓存
System.out.println(user1);
System.out.println(user2);
System.out.println(user3);
System.out.println(user4);
sqlSession.commit(); // 清空缓存
User user5 = userMapper.selectUserById(10); // 查询数据库
sqlSession.close();
}
private Integer inserUser() {
User user = new User();
user.setUsername("风华哥");
user.setPassword("别吹水了..");
user.setAge(35);
Integer affectedRows = userMapper.insertUser(user);
sqlSession.commit();
return affectedRows;
}
二级缓存Mybatis的二级缓存默认是没有开启的。Mybatis的二级缓存是NameSpace级别的,也就是说,他不受制与我们同一个sqlSession的限制。也就是说只要是同一个Namespace,那么他就会去走二级缓存(Map)
那么二级缓存怎么开启呢?
1 二级缓存开启
<!--二级缓存开启-->
<setting name="cacheEnabled" value="true" />
2 需要去给我们需要缓存的JavaBean实现序列化接口,生成序列化id 开启idea设置
3 在我们需要开启二级缓存的mapper.xml中配置以下标签<cache/>
使用二级缓存
// 测试二级缓存
// Cache Hit Ratio [com.cskaoyan.mapper.UserMapper]: 0.0 这个表示二级缓存已经开启,但是没有命中
@Test
public void testSelectUserById5(){
SqlSession sqlSession1 = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
SqlSession sqlSession3 = sqlSessionFactory.openSession();
SqlSession sqlSession4 = sqlSessionFactory.openSession();
UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);
UserMapper userMapper4 = sqlSession4.getMapper(UserMapper.class);
User user1 = userMapper1.selectUserById(10); // 执行查询
sqlSession1.commit(); // 把结果放入二级缓存
/**
* Cache Hit Ratio [com.cskaoyan.mapper.UserMapper]: 0.5
* Cache Hit Ratio [com.cskaoyan.mapper.UserMapper]: 0.6666666666666666
* Cache Hit Ratio [com.cskaoyan.mapper.UserMapper]: 0.75
*
*/
User user2 = userMapper2.selectUserById(10);
User user3 = userMapper3.selectUserById(10);
User user4 = userMapper4.selectUserById(10);
System.out.println(user1);
System.out.println(user2);
System.out.println(user3);
System.out.println(user4);
}
问题1: 我们需要去了解一下一级缓存和二级缓存的运行结构图
问题2:我们需要去看一下Mybatis的缓存是用什么数据结构(Map)来存的,简单看一下他的源码
Mybatis针对缓存给提供了一个接口,org.apache.ibatis.cache.Cache
Map里面的Key:就是sql语句+ 参数
value: 就是我们执行完sql获取到的结果
总结:Mybatis本质上只是一个ORM框架,是帮助我们去访问数据库,提高效率的一个框架。缓存这一块不是他的强项,所以一般我们如果要使用缓存,不会使用Mybatis给我们提供的缓存。那么我们使用什么来缓存呢?
Nosql数据库:Memcache、Redis