MyBatis完整教程IDEA版(3)--动态SQL/MyBatis缓存
【狂神说Java】Mybatis最新完整教程IDEA版通俗易懂: P22 - P32
1、动态SQL
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。if
choose (when, otherwise)
trim (where, set)
foreach
1.1、搭建环境
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 String id;private String title;private String author;private Date createTime;private int views; } -
编写实体类对应的Mapper接口 和 Mapper.xml文件
准备工作:
@Test
public void test() {SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);Blog blog = new Blog();blog.setId(IdUtils.getId());blog.setTitle("Mybatis");blog.setAuthor("凌波粒");blog.setCreateTime(new Date());blog.setViews(9999);mapper.addBlog(blog);blog.setId(IdUtils.getId());blog.setTitle("Java");mapper.addBlog(blog);blog.setId(IdUtils.getId());blog.setTitle("Spring");mapper.addBlog(blog);blog.setId(IdUtils.getId());blog.setTitle("微服务");mapper.addBlog(blog);sqlSession.close();
}
1.2、If
Mapper接口编写
//查询博客
List<Blog> queryBlogIf(Map<String, Object> map);
Mapper.xml文件编写,使用if
<select id="queryBlogIf" parameterType="map" resultType="Blog">select * from blog where 1=1<if test="title != null">and title = #{title}</if><if test="author != null">and author = #{author}</if>
</select>
测试
@Testpublic void queryBlogIf(){SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);Map<String, Object> map = new HashMap<>();
// map.put("title", "Mybatis");map.put("author", "凌波粒");List<Blog> blogs = mapper.queryBlogIf(map);for (Blog blog : blogs) {System.out.println(blog);}sqlSession.close();}
1.3、choose (when, otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="com.lingbo.pojo.Blog">select * from blog<where><choose><when test="title != null">title = #{title}</when><when test="author != null">author = #{author}</when><when test="views != null">views = #{views}</when><otherwise></otherwise></choose></where>
</select>
1.4、trim (where, set)
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
select * from blog
<where>
<if test="title != null">title = #{title}
</if>
<if test="author != null">and author = #{author}
</if>
</where>
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
<update id="updateBlog" parameterType="map">update blog<set><if test="title != null">title = #{title},</if><if test="author != null">author = #{author}</if></set>where id = #{id};
</update>
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面去执行一些逻辑代码。
1.5、foreach
<!--select * from user where 1=1 and (id=1 or id=2 or id=3)我们现在传递一个万能的map,这个map中可以存在一个集合!--><select id="queryBlogForeach" resultType="com.lingbo.pojo.Blog" parameterType="map">select * from blog<where><foreach collection="ids" item="id" open="and (" close=")" separator="or">id = #{id}</foreach></where></select>
1.6、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 blog<where><include refid="if-title-author"></include></where> </select>
注意事项:
- 最好基于单表来定义SQL片段!
- 不要存在where标签
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
- 先在MySQL中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!
2、缓存
2.1、简介
查询-------->连接数据库(耗资源)一次查询的结果,给他暂存在一个可以直接取到的地方!-->内存:缓存我们再次查询相同数据的时候,直接走缓存,就不用走数据库了。
- 什么是缓存 [Cache ]?
- 存在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
- 什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。
2.2、MyBatis缓存
- MyBatis包含一个非常强大的査询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(Sqlsession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存。
2.3、一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试步骤:
-
开启日志
<settings><!--标准的日志工厂的实现--><setting name="logImpl" value="STDOUT_LOGGING"/> </settings> -
测试在一个Session中查询两次相同的记录
-
查看日志输出

缓存失效的情况:
-
查询不同的记录
-
增删改操作可能会改变原来的数据,所以必定会刷新缓存!

-
查询不同的Mapper.xml
-
手动清理缓存!

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!
一级缓存就是一个Map。
2.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存:
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了:但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容。
- 不同的mapper查出的数据会放在自己对应的缓存(map)中;
步骤:
-
开启全局缓存
<settings><!--显式的开启全局缓存--><setting name="cacheEnabled" value="true"/> </settings> -
在要使用二级缓存的Mapper中开启
<!-- 在当前Mapper.xml中使用二级缓存 --> <cache/>也可以自定义一些参数
<!-- 在当前Mapper.xml中使用二级缓存 --> <cache eviction="FIFO"flushInterval="60000"size="512"readOnly="true"/> -
测试
-
问题:我们需要将实体类序列化!否则就会报错!
Caused by: java.io.NotSerializableException: com.lingbo.pojo.User
-
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效!
- 所有的数据都会先放在一级缓存中;
- 只有当会话(SqlSession)提交,或者关闭的时候,才会提交到二级缓存中!
2.5、缓存原理

2.6、自定义缓存-ehcache
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存。
要在程序中使用ehcache,先要导包!
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.1.0</version>
</dependency>
在mapper中指定使用我们的ehcache实现
<!-- 在当前Mapper.xml中使用二级缓存 -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
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"/><defaultCacheeternal="false"maxElementsInMemory="10000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="259200"memoryStoreEvictionPolicy="LRU"/><cachename="cloud_user"eternal="false"maxElementsInMemory="5000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="1800"timeToLiveSeconds="1800"memoryStoreEvictionPolicy="LRU"/>
</ehcache>
