Powered By JamPang
QQ:847885907
https://jampang.cn/
Mybatis笔记
这个是第三部分
12、动态SQL
项目:Mybatis-08
什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句
利用动态SQL这一特性可以彻底摆脱这种痛苦。
动态sQL元素和JSTL 或基于类似XML的文本处理器相似。在MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis3大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于OGNL的表达式来淘汰其它大部分元素。
if
choose (when, otherwise)
trim (where, set)
foreach12.1、搭建环境
Mysql:
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创建一个基础工程
- 导包
- 编写配置文件 - 驼峰命名开启mybatis-config.xml - <!--是否开启驼峰命名自动映射--> <setting name="mapUnderscoreToCamelCase" value="true"/>
- 编写实体类 - @Data public class Blog { private int id; private String title; private String author; private Date createTime; private int views; }
- 编写实体类对象的Mapper接口和Mapper.xml文件 - //插入数据 int addBlog(Blog blog);- <insert id="addBlog" parameterType="blog"> insert into mybatis.blog(id, title, author, create_time, views) values (##{id}, ##{title}, ##{author}, ##{createTime}, ##{views}); </insert>
- 测试类 - @Test public void addInitBlog(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Blog blog = new Blog(); blog.setId(IDUtils.getId()); blog.setTitle("Mybatis-08动态Sql-01"); blog.setAuthor("Jam"); blog.setCreateTime(new Date()); blog.setViews(9999); mapper.addBlog(blog); blog.setId(IDUtils.getId()); blog.setTitle("Mybatis-08动态Sql-02"); mapper.addBlog(blog); blog.setId(IDUtils.getId()); blog.setTitle("Mybatis-08动态Sql-03"); mapper.addBlog(blog); sqlSession.close(); }
12.2、Where、IF语句
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where元素也会将它们去除。
 <select id="queryBlogIF" parameterType="map" resultType="Blog">
    select * from mybatis.blog
     <where>
         <if test="title != null">
        and title = ##{title}
        </if>
            <if test="author != null">
                and author = ##{author}
        </if>
     </where>
</select>测试类
@Test
public void queryBlogIF(){
   SqlSession sqlSession = MybatisUtils.getSqlSession();
   BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
   map.put("title","Mybatis-08动态Sql-02");
   map.put("author","Jam");
   List<Blog> blogs = mapper.queryBlogIF(map);
   for (Blog blog : blogs) {
       System.out.println(blog);
   }
   sqlSession.close();
}12.3、choose(when, otherwise)
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
<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>测试类
@Test
public void queryBlogChoose(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    map.put("title","Mybatis-08动态Sql-02");
    //map.put("author","Jam");
    map.put("views",9999);
    List<Blog> blogs = mapper.queryBlogChoose(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}12.4、trim(where, set)
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
where参考上面的xml代码 12.2 12.3
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号
set方法
<!-- Update -->
<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>测试类
@Test
public void updateBlog(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    //map.put("title","Mybatis-08动态Sql-01-Set修改");
    map.put("author","Jammm2");
    map.put("id","d7935793c82c4358a17b955d2b99f2eb");
    mapper.updateBlog(map);
    sqlSession.close();
}==所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面去执行一个逻辑代码==
if where set choose when
12.5、Foreach

我们来先看下数据库表中的数据
| id | title | author | create_time | views | 
|---|---|---|---|---|
| d7935793c82c4358a17b955d2b99f2eb | Mybatis-08动态Sql-01-Set修改 | Jammm2 | 2020-05-06 00:32:40 | 9999 | 
| e6c723dcd4e24eaaa59984e89be02699 | Mybatis-08动态Sql-02 | Jam | 2020-05-06 00:32:40 | 9999 | 
| 8dca0287e4f841a88457f9c28af8e382 | Mybatis-08动态Sql-03 | Jam | 2020-05-06 00:32:40 | 9999 | 
下面为了方便查询我们把id改成1,2,3
| id | title | author | create_time | views | 
|---|---|---|---|---|
| 1 | Mybatis-08动态Sql-01-Set修改 | Jammm2 | 2020-05-06 00:32:40 | 9999 | 
| 2 | Mybatis-08动态Sql-02 | Jam | 2020-05-06 00:32:40 | 9999 | 
| 3 | Mybatis-08动态Sql-03 | Jam | 2020-05-06 00:32:40 | 9999 | 
BlogMapper.xml
<!-- queryBlogForeach
    select * from mybatis.blog where 1=1 and(id=1 or id=2 or id=3)
    我们现在传递一个万能的map,这个map中可以存在一个集合
    collection:集合名称,item:集合中遍历出每一项的名称,open:开始标识,close:结束标识,separator:分隔符
    -->
<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>测试类
@Test
public void queryBlogForeach(){
   SqlSession sqlSession = MybatisUtils.getSqlSession();
   BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    ArrayList<Integer> ids = new ArrayList<Integer>();
    ids.add(1);
    ids.add(2);
    ids.add(3);
    map.put("ids",ids);
    List<Blog> blogs = mapper.queryBlogForeach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}==动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了。==
建议:
- 先写出完整的SQL语句,再对应的去修改成动态SQL,实现通用即可。
12.6、SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用
- 使用SQL标签抽取公共的部分 - <sql id="if-title-author"> <if test="title != null"> title = ##{title}, </if> <if test="author != null"> author = ##{author} </if> </sql>
- 在需要使用过的地方使用Include标签引用即可 - <select id="queryBlogIF2" parameterType="map" resultType="Blog"> select * from mybatis.blog <where> <include refid="if-title-author"></include> </where> </select>
注意事项:
- 最好基础单表来定义SQL片段
- 不要存在where标签
13、缓存
项目:mybatis-09
查询 → 连接数据库  消耗资源
一次查询结果,暂存在一个可以直接取到的地方 → 内存:缓存
再次查询相同数据的时候,不用连接数据库,而是从缓存中读取。13.1、简介
- 什么是缓存[Cache]? - 存在在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的问题。
 
- 为什么使用缓存? - 减少和数据库的交互次数,减少系统开销,提高系统效率。
 
- 什么样的数据能使用缓存? - 经常查询并且不经常改变的数据。【可以使用缓存】
 
13.2、Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两极缓存:一级缓存和二级缓存 - 默认情况下,只有一级缓存开启。 (SqlSession级别的缓存, 也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存。
 
13.3、一级缓存
- 一级缓存也叫本地缓存 - 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库。
 
测试步骤:
- 开启日志
- 测试在一个Session中查询两次相同的记录 - java - //根据ID查询用户 User queryUserById(@Param("id") int id);- xml - <select id="queryUserById" resultType="user"> select * from mybatis.user where id = ##{id} </select>- 测试类 - @Test public void queryUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); System.out.println("======================================="); User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user==user2); sqlSession.close(); }
- 查看日志输出 - Opening JDBC Connection Created connection 156545103. ==> Preparing: select * from mybatis.user where id = ? ==> Parameters: 1(Integer) <== Columns: id, name, pwd <== Row: 1, jam, 123 <== Total: 1 User(id=1, name=jam, pwd=123) ======================================= User(id=1, name=jam, pwd=123) true Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@954b04f] Returned connection 156545103 to pool. Process finished with exit code 0
缓存失效的情况:
- 查询不同的内容
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存! - 添加一个修改方法 - java - //修改用户 int updateUser(User user);- xml - <update id="updateUser" parameterType="user"> update mybatis.user set name=##{name},pwd=##{pwd} where id=##{id} </update>- 测试类 - @Test public void queryUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryUserById(1); System.out.println(user); System.out.println("======================================="); mapper.updateUser(new User(2,"aaa","bbb")); User user2 = mapper.queryUserById(1); System.out.println(user2); System.out.println(user==user2); sqlSession.close(); }- 日志: - Opening JDBC Connection ==> Preparing: select * from mybatis.user where id = ? ==> Parameters: 1(Integer) <== Columns: id, name, pwd <== Row: 1, jam, 123 <== Total: 1 User(id=1, name=jam, pwd=123) ======================================= ==> Preparing: update mybatis.user set name=?,pwd=? where id=? ==> Parameters: aaa(String), bbb(String), 2(Integer) <== Updates: 1 ==> Preparing: select * from mybatis.user where id = ? ==> Parameters: 1(Integer) <== Columns: id, name, pwd <== Row: 1, jam, 123 <== Total: 1 User(id=1, name=jam, pwd=123) false Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@954b04f] Returned connection 156545103 to pool. Process finished with exit code 0
- 查询不同的Mapper.xml
- 手动清理缓存 - sqlSession.clearCache();
小结:一级缓存是默认开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段。
 也可以这么理解:一级缓存就是一个Map
13.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存。
- 基于namespace级别的缓存, 一个名称空间,对应一个二级缓存;
- 工作机制: - 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中。
 
步骤:
- 开启全局缓存 - 在mybatis-config.xml中添加 - <!--显示的开启全局缓存--> <setting name="cacheEnabled" value="true"/>
- 在要使用二级缓存的Mapper.xml中开启 - <!--在当前Mapper.xml中使用二级缓存--> <cache/>- 也可以自定义参数 - <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>- 这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。 - evication: - LRU– 最近最少使用:移除最长时间不被使用的对象。【默认】
- FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
- SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
- WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
 
- 测试 - 问题:在Mapper.xml中直接声明"<cache/>"报错,我们需要将实体类序列化。 - Caused by: java.io.NoSerializbleException:com.jam.pojo.User- 在POJO的类中 implements Serializable 
- 执行结果 - Opening JDBC Connection ==> Preparing: select * from mybatis.user where id = ? ==> Parameters: 1(Integer) <== Columns: id, name, pwd <== Row: 1, jam, 123 <== Total: 1 User(id=1, name=jam, pwd=123) Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2f0a87b3] Returned connection 789219251 to pool. Cache Hit Ratio [com.jam.dao.UserMapper]: 0.5 User(id=1, name=jam, pwd=123) true Process finished with exit code 0
 
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交或者关闭的时候,才会提交到二级缓存中。
13.5、缓存原理
缓存顺序:
- 先看二级缓存中有没有
- 再看一级缓存中有没有
- 查询数据库

13.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.2.1</version>
</dependency>再在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:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
           user.home – 用户主目录
           user.dir  – 用户当前工作目录
           java.io.tmpdir – 默认临时文件路径
         -->
        <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"/>
        <!--
           defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
         -->
        <!--
          name:缓存名称。
          maxElementsInMemory:缓存最大数目
          maxElementsOnDisk:硬盘最大缓存个数。
          eternal:对象是否永久有效,一但设置了,timeout将不起作用。
          overflowToDisk:是否保存到磁盘,当系统当机时
          timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
          timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
          diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
          diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
          diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
          memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
          clearOnFlush:内存数量最大时是否清除。
          memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
          FIFO,first in first out,这个是大家最熟的,先进先出。
          LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
          LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
       -->
</ehcache>不需要深入,工作中现在一般都是Redis数据库(K-V)。
本文共 2447 个字数,平均阅读时长 ≈ 7分钟
 
                                
             
         
             
                
评论 (0)