MyBatis 动态SQL、缓存(一级缓存、二级缓存、自定义缓存)

动态SQL

什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句

动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多
元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。
MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

if
choose (when, otherwise)
trim (where, set)
foreach
搭建环境
CREATE TABLE `blog` (
  `id` varchar(50) NOT NULL COMMENT 'id',
  `title` varchar(100) NOT NULL COMMENT 'title',
  `author` varchar(30) NOT NULL COMMENT 'author',
  `create_time` datetime NOT NULL COMMENT 'create_time',
  `views` int(30) NOT NULL COMMENT 'views'
) ENGINE=InnoDB DEFAULT CHARSET=utf8

INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('1', 'Java SE-1', '巡山的小白', '2019-10-17 18:38:02', '100'); 
INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('2', 'Java SE-2', '巡山的小白', '2019-10-16 18:39:22', '200');
INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('3', 'Java SE-3', '小白的巡山', '2019-10-18 18:39:58', '200');
INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('4', 'Java SE-4', '小白的巡山', '2019-10-15 18:40:46', '300');
INSERT INTO `blog` (`id`, `title`, `author`, `create_time`, `views`) VALUES ('5', 'Java 从入门到放弃', '小白不背锅', '2019-10-14 18:41:42', '1');

编写一个基础工程

  1. 导包
  2. 编写配置文件
  3. 编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
    private Integer id;
    private String title;
    private String author;
    private Date createTime;
    private Integer views;
}
  1. 编写实体类对应Mapper接口 和 Mapper.xml文件
1. IF

介绍:
根据你给的条件(可以多个条件)拿到信息,相当于 Java 中的 IF 语句,if 条件可以叠加

  1. 在 mapper 接口编写 IF 的动态SQL方法,代码如下:
//根据 map 集合存查询的条件
List<Blog> queryBlogIF(Map map);
  1. 在 mapper 接口对应的 xml 配置文件中编写 select 语句,代码如下:
<select id="queryBlogIF" resultType="Blog" parameterType="map">
    select * from mybatis.blog where 1=1
    <if test="id != null">
        and id = #{id}
    </if>
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
    <if test="createTime != null">
        and create_time = #{createTime}
    </if>
    <if test="views != null">
        and views = #{views}
    </if>
</select>
  1. 利用 @Test 注解进行测试,代码如下:
@Test
public void queryBlogIF(){
    SqlSession sqlsession = mybatisUtils.getSqlsession();
    blogMapper mapper = sqlsession.getMapper(blogMapper.class);
    HashMap map = new HashMap();
    map.put("author","巡山的小白");
    List<Blog> blogs = mapper.queryBlogIF(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlsession.close();
}
  1. 注意点:
    测试的时候 map 集合里的键值与 xml 配置文件中 IF 标签 test 里的 XX !=NULL的 XX 名字一样
2. Choose (when, otherwise)

介绍:
根据你给的条件(可以多个条件,但是只匹配 xml 配置文件中靠前的条件)拿到信息,类似于 Java 的 switch-case 语句

  1. 在 mapper 接口编写 Choose 的动态SQL方法,代码如下:
List<Blog> queryBlogChoose(Map map);
  1. 在 mapper 接口对应的 xml 配置文件中编写 select 语句,代码如下:
<select id="queryBlogChoose" resultType="Blog" parameterType="map">
    select * from mybatis.blog
    <where>
        <choose>
            <when test="id != null">
                id = #{id}
            </when>
            <when test="title != null">
                and title = #{title}
            </when>
            <when test="author != null">
                and author = #{author}
            </when>
            <when test="createTime != null">
                and create_time = #{createTime}
            </when>
            <when test="views != null">
                and views = #{views}
            </when>
        </choose>
    </where>
</select>
  1. 利用 @Test 注解进行测试,代码如下:
@Test
public void queryBlogChoose(){
    SqlSession sqlsession = mybatisUtils.getSqlsession();
    blogMapper mapper = sqlsession.getMapper(blogMapper.class);
    HashMap map = new HashMap();
    map.put("author","小白的巡山");
    map.put("view",200);
    List<Blog> blogs = mapper.queryBlogChoose(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlsession.close();
}
  1. 图解
    MyBatis 动态SQL、缓存(一级缓存、二级缓存、自定义缓存)_第1张图片
3. trim (where,set)

介绍:

  • where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
  • set 元素会动态前置 SET 关键字,同时也会删掉无关的逗号,因为用了条件语句之后很可能就会在生成的 SQL 语句的后面留下这些逗号。
  1. 在 mapper 接口编写 trim 的动态SQL方法,代码如下:
List<Blog> queryBlogTrime(Map map);
Integer updateBlogTrime(Map map);
  1. 在 mapper 接口对应的 xml 配置文件中编写 select 和 update 语句,代码如下:
<select id="queryBlogTrime" resultType="Blog" parameterType="map">
    select * from mybatis.blog
    <where>
        <if test="id != null">
            id = #{id}
        </if>
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
        <if test="createTime != null">
            and create_time = #{createTime}
        </if>
        <if test="views != null">
            and views = #{views}
        </if>
    </where>
</select>
<update id="updateBlogTrime" parameterType="map">
    update mybatis.blog
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author},
        </if>
        <if test="createTime != null">
            create_time = #{createTime},
        </if>
        <if test="views != null">
            views = #{views}
        </if>
    </set>
    where id = #{id}
</update>
  1. 利用 @Test 注解进行测试,代码如下:
@Test
public void queryBlogTrime(){
    SqlSession sqlsession = mybatisUtils.getSqlsession();
    blogMapper mapper = sqlsession.getMapper(blogMapper.class);
    HashMap map = new HashMap();
    map.put("author","小白的巡山");
    map.put("views",200);
    List<Blog> blogs = mapper.queryBlogTrime(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlsession.close();
}
@Test
public void updateBlogTrime(){
    SqlSession sqlsession = mybatisUtils.getSqlsession();
    blogMapper mapper = sqlsession.getMapper(blogMapper.class);
    HashMap map = new HashMap();
    map.put("id",4);
    map.put("author","小白不背锅");
    Integer result = mapper.updateBlogTrime(map);
    if(result>0){
        System.out.println("更新成功...");
        sqlsession.commit();
    }else {
        System.out.println("更新失败...");
    }
    sqlsession.close();
}
4. SQL片段

有的时候,我们会将一些常用的 CRUD 代码抽取出来,方便下次复用!

  1. 使用SQL标签抽取公共的部分
<sql id="If-Not-Null">
    <if test="id != null">
        id = #{id}
    </if>
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
    <if test="createTime != null">
        and create_time = #{createTime}
    </if>
    <if test="views != null">
        and views = #{views}
    </if>
</sql>
  1. 在需要使用的地方使用Include标签引用即可
<select id="queryBlogTrime" resultType="Blog" parameterType="map">
    select * from mybatis.blog
    <where>
        <include refid="If-Not-Null"></include>
    </where>
</select>
  1. 使用 SQL 标签需要注意的地方
    • 最好基于单表来定义 SQL 片段!
    • 不要存在 where 和 set 标签
5. Foreach

动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候。比如:

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

官方文档的解释:
MyBatis 动态SQL、缓存(一级缓存、二级缓存、自定义缓存)_第2张图片
自己实现 foreach 功能:

  1. 在 xml 配置文件中编写相应的sql语句
<select id="queryBlogForeach" resultType="Blog" parameterType="list">
    select * from blog where id in 
    <foreach collection="list" item="BlogId" open="(" separator="," close=")">
        #{BlogId}
    </foreach>
</select>
  1. 利用 @Test 注解进行测试:
public void queryBlogForeach(){
    SqlSession sqlsession = mybatisUtils.getSqlsession();
    blogMapper mapper = sqlsession.getMapper(blogMapper.class);
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    List<Blog> blogs = mapper.queryBlogForeach(list);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlsession.close();
}
  1. 需要注意的地方:
    MyBatis 动态SQL、缓存(一级缓存、二级缓存、自定义缓存)_第3张图片

缓存

1. 简介

查询 : 需要连接数据库 ,耗费资源!

如果我们将一次查询的结果,给他暂存在一个可以直接取到的地方!----> 缓存

我们再次查询相同数据的时候,直接走缓存,就不用走数据库了,这样就可以省时省力

  • 什么是缓存 [ Cache ]?
    • 存在内存中的临时数据。
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
  • 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销,提高系统效率。
  • 什么样的数据能使用缓存?
    • 经常查询并且不经常改变的数据。【可以使用缓存】
2. MyBatis缓存
  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存,缓存可以极大的提升查询效率。
  • MyBatis系统中默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于 namespace 级别的缓存。
    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
3. 一级缓存
  • 一级缓存也叫本地缓存: SqlSession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

测试步骤:

  1. 在mybatis核心配置文件中开启日志

    

  1. 测试在一个Sesion中查询两次相同记录
@Test
public void queryBlogs(){
    SqlSession sqlsession = mybatisUtils.getSqlsession();
    blogMapper mapper = sqlsession.getMapper(blogMapper.class);
    List<Blog> blogs = mapper.queryBlogs();
    System.out.println(blogs);
    List<Blog> blogs1 = mapper.queryBlogs();
    System.out.println(blogs1);
    sqlsession.close();
}
  1. 查看日志输出
    MyBatis 动态SQL、缓存(一级缓存、二级缓存、自定义缓存)_第4张图片

缓存失效的情况:

  1. 查询不同的东西
  2. 进行过增删改操作后,可能会改变原来的数据,所以必定会刷新缓存!
  3. 查询不同的Mapper.xml
  4. 手动清理缓存!
    MyBatis 动态SQL、缓存(一级缓存、二级缓存、自定义缓存)_第5张图片
    小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!一级缓存就是一个Map。
4. 二级缓存
  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果当前会话(SqlSession)关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

步骤:

  1. 开启全局缓存


  1. 在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>

也可以自定义参数

<!--在当前Mapper.xml中使用二级缓存-->
<cache  eviction="FIFO"
       flushInterval="60000"
       size="512"
       readOnly="true"/>
  1. 让原有的 pojo 类实现 Serializable 接口,使实体类序列化,以免报下列错误:
    Caused by: java.io.NotSerializableException: cn.edu.xiyou.Blog
  2. 利用 @Test 注解进行测试:
@Test
public void queryBlogs(){
    SqlSession sqlsession1 = mybatisUtils.getSqlsession();
    blogMapper mapper1 = sqlsession1.getMapper(blogMapper.class);
    SqlSession sqlsession2 = mybatisUtils.getSqlsession();
    blogMapper mapper2= sqlsession2.getMapper(blogMapper.class);
    Blog blog1 = mapper1.queryBlogById(1);
    System.out.println(blog1);
    //关闭第一个sqlsession
    sqlsession1.close();
    //让第二个sqlsession会话查询同一条数据
    Blog blog = mapper2.queryBlogById(1);
    System.out.println(blog);
    sqlsession2.close();
}

测试结果:
MyBatis 动态SQL、缓存(一级缓存、二级缓存、自定义缓存)_第6张图片
总结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中;
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!
5. 缓存原理

MyBatis 动态SQL、缓存(一级缓存、二级缓存、自定义缓存)_第7张图片

6. 自定义缓存-ehcache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

  1. 要在程序中使用ehcache,先要在pom.xml中导入依赖!


    org.mybatis.caches
    mybatis-ehcache
    1.1.0

  1. 在mapper.xml中指定使用我们的ehcache缓存实现!
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  1. 在resources包下新建ehcache.xml配置文件

<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>

你可能感兴趣的:(SSM)