动态SQL和MyBatis的缓存

一、动态SQL

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了 解决 拼接SQL语句字符串时的痛点问题。

1、if

if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之 标签中的内容不会执行

   <select id="getEmpByConditionOne" 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="gender !=null and gender!=''">
            and gender=#{gender}
        </if>
    </select>

2、where

where和if一般结合使用:
a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and去掉
注意:where标签不能去掉条件最后多余的and

<select id="getEmpByCondition" resultType="emp">
        select * from t_emp
        <where>
            <if test="empName !=null and empName != ''">
                emp_name=#{empName}
            </if>
            <if test="age!=null and age!=''">
                and age=#{age}
            </if>
            <if test="gender !=null and gender!=''">
                and gender=#{gender}
            </if>
        </where>
    </select>

3、trim

trim用于去掉或添加标签中的内容
常用属性:
prefix:在trim标签中的内容的前面添加某些内容
prefixOverrides:在trim标签中的内容的前面去掉某些内容
suffix:在trim标签中的内容的后面添加某些内容
suffixOverrides:在trim标签中的内容的后面去掉某些内容

<select id="getEmpByCondition" resultType="emp">
        select * from t_emp
        <trim prefix="where" suffixOverrides="and">
            <if test="empName !=null and empName != ''">
                emp_name=#{empName} and
            </if>
            <if test="age!=null and age!=''">
                age=#{age} and
            </if>
            <if test="gender !=null and gender!=''">
                gender=#{gender}
            </if>
        </trim>
</select>

4、choose、when、otherwise

choose、when、 otherwise相当于if…else if…else

when至少设置一个,otherwise最多设置一个

<select id="getEmpByChoose" 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="gender!=null and gender!='' ">
                    gender=#{gender}
                </when>
            </choose>
        </where>
</select>

5、foreach

批量操作

collection:设置要循环的数组或集合

item:用一个字符串表示数组或集合中的每一个数据

separator:设置每次循环的数据之间的分隔符

open:循环的所有内容以什么开始

close:循环的所有内容以什么结束

<insert id="insertMoreEmp">
        insert into t_emp value
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.gender},null)
        </foreach>
    </insert>

    <!--    void deleteMoreEmp(@Param("empIds") Integer[] empIds);-->
    <delete id="deleteMoreEmp">
<!--        delete from t_emp where emp_id in-->
<!--        (-->
<!--        <foreach collection="empIds" item="empId" separator=",">-->
<!--            #{empId}-->
<!--        </foreach>-->
<!--        )-->
<!--        delete from t_emp where emp_id in-->
<!--        <foreach collection="empIds" item="empId" separator="," open="(" close=")">-->
<!--            #{empId}-->
<!--        </foreach>-->

        delete from t_emp where
        <foreach collection="empIds" item="empId" separator="or" >
            emp_id=#{empId}
        </foreach>

    </delete>

6、SQL片段

sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入

<!--设置sql片段-->
<sql id="empColumns">
        emp_id,emp_name,age,gender,dept_id
</sql>	
<!--调用sql片段-->
<include refid="empColumns"></include>

二、MyBatis的缓存

1、MyBatis的一级缓存(默认开启的)

一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就
会从缓存中直接获取,不会从数据库重新访问

1.1使用案例

	/**
     * MyBatis的一级缓存:
     * MyBatis的一级缓存是SqlSession级别的,即通过同一个SqlSession查询的数据会被缓存
     * 再次使用同一个SqlSession查询同一条数据 ,会从缓存中获取
     */

    @Test
    public void testGetEmpById(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
        Emp emp1 = mapper.getEmpById(1);
        Emp emp2 = mapper.getEmpById(1);
        System.out.println(emp1);
        System.out.println(emp2);
        sqlSession.close();
    }

产生的调试信息:

Connected to the target VM, address: '127.0.0.1:63940', transport: 'socket'
DEBUG 10-12 17:39:00,069 ==>  Preparing: select * from t_emp where emp_id=? (BaseJdbcLogger.java:137) 
DEBUG 10-12 17:39:00,095 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137) 
DEBUG 10-12 17:39:00,110 <==      Total: 1 (BaseJdbcLogger.java:137) 
Emp{empId=1, empName='张三', age=20, gender='男'}
Emp{empId=1, empName='张三', age=20, gender='男'}
Disconnected from the target VM, address: '127.0.0.1:63940', transport: 'socket'

通过调试信息也可以看出只调用了一次sql语句

当查询不同的信息时,就会产生不同的调试信息:

		Emp emp1 = mapper.getEmpById(1);
        Emp emp2 = mapper.getEmpById(2);
        System.out.println(emp1);
        System.out.println(emp2);

产生的调试信息:

Connected to the target VM, address: '127.0.0.1:54568', transport: 'socket'
DEBUG 10-12 17:41:28,975 ==>  Preparing: select * from t_emp where emp_id=? (BaseJdbcLogger.java:137) 
DEBUG 10-12 17:41:29,001 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137) 
DEBUG 10-12 17:41:29,017 <==      Total: 1 (BaseJdbcLogger.java:137) 
DEBUG 10-12 17:41:29,017 ==>  Preparing: select * from t_emp where emp_id=? (BaseJdbcLogger.java:137) 
DEBUG 10-12 17:41:29,017 ==> Parameters: 2(Integer) (BaseJdbcLogger.java:137) 
DEBUG 10-12 17:41:29,018 <==      Total: 1 (BaseJdbcLogger.java:137) 
Emp{empId=1, empName='张三', age=20, gender='男'}
Emp{empId=2, empName='李四', age=21, gender='男'}
Disconnected from the target VM, address: '127.0.0.1:54568', transport: 'socket'

通过调试信息我们可以明显的看出调用了两次sql语句(这种情况就是同一个SqlSession但是查询的条件不同所对应的情况,其他情况不在赘述)

1.2使一级缓存失效的四种情况:

  1. 不同的SqlSession对应不同的一级缓存
  2. 同一个SqlSession但是查询条件不同
  3. 同一个SqlSession两次查询期间执行了任何一次增删改操作(在执行增删改操作后自动清空缓存)
  4. 同一个SqlSession两次查询期间手动清空了缓存

2、MyBatis的二级缓存

二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被
缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
二级缓存开启的条件:
a>在核心配置文件中,设置全局配置属性cacheEnabled=“true”,默认为true,不需要设置
b>在映射文件中设置标签
c>二级缓存必须在SqlSession关闭或提交之后有效(一级缓存失效后会将数据放到二级缓存中)
d>查询的数据所转换的实体类类型必须实现序列化的接口
使二级缓存失效的情况:
两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效

2.1使用案例

b>在映射文件中设置标签

<mapper namespace="com.atguigu.mybatis.mapper.CacheMapper">
    <cache/>

d>查询的数据所转换的实体类类型必须实现序列化的接口

public class Emp implements Serializable {}
	@Test
    public void testCache() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = builder.build(inputStream);
        SqlSession sqlSession1 = build.openSession(true);
        CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
        Emp emp1 = mapper1.getEmpById(1);
        System.out.println(emp1);
        sqlSession1.close();//c>二级缓存必须在SqlSession关闭或提交之后有效
        SqlSession sqlSession2 = build.openSession(true);
        CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
        Emp emp2 = mapper2.getEmpById(1);
        System.out.println(emp2);
        sqlSession2.close();
    }

3、二级缓存的相关配置

在mapper配置文件中添加的cache标签可以设置一些属性:
①eviction属性:缓存回收策略,默认的是 LRU。
LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
SOFT – 软引用:移除基于垃圾 回收器状态和软引用规则的对象。
WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
②flushInterval属性:刷新间隔,单位毫秒
默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
③size属性:引用数目,正整数
代表缓存最多可以存储多少个对象,太大容易导致内存溢出
④readOnly属性:只读, true/false
true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了 很重
要的性能优势。
false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是
false。

4、MyBatis缓存查询的顺序

先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。
如果二级缓存没有命中,再查询一级缓存
如果一级缓存也没有命中,则查询数据库
SqlSession关闭之后,一级缓存中的数据会写入二级缓存

5、整合第三方缓存EHCache

5.1、添加依赖(在pom.xml中添加)

<!-- Mybatis EHCache整合包 -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<!-- slf4j日志门面的一个具体实现 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>

5.2、各jar包的功能

jar包名称作用
mybatis-ehcacheMybatis和EHCache的整合包
ehcacheEHCache核心包
slf4j-apiSLF4J日志门面包
logback-classic支持SLF4J门面接口的一个具体实现

5.3、创建EHCache的配置文件ehcache.xml

<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!-- 磁盘保存路径 -->
    <diskStore path="D:\atguigu\ehcache"/>
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

5.4、设置二级缓存的类型

<mapper namespace="com.atguigu.mybatis.mapper.CacheMapper">
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

5.5、加入logback日志

存在SLF4J时,作为简易日志的log4j将失效,此时我们需要借助SLF4J的具体实现logback来打印日志。 创建logback的配置文件logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 指定日志输出的位置 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 日志输出的格式 -->
<!-- 按照顺序分别是: 时间、日志级别、线程名称、打印日志的类、日志主体内容、换行
-->
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger]
[%msg]%n</pattern>
</encoder>
</appender>
<!-- 设置全局日志级别。日志级别按顺序分别是: DEBUG、INFO、WARN、ERROR -->
<!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
<root level="DEBUG">
<!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
<appender-ref ref="STDOUT" />
</root>
<!-- 根据特殊需求指定局部日志级别 -->
<logger name="com.atguigu.mybatis.mapper" level="DEBUG"/>
</configuration>

5.6、EHCache配置文件说明

属性名


作用
maxElementsInMemory在内存中缓存的element的最大数目
maxElementsOnDisk在磁盘上缓存的element的最大数目,若是0表示无
穷大
eternal设定缓存的elements是否永远不过期。 如果为
true,则缓存的数据始终有效, 如果为false那么还
要根据timeToIdleSeconds、timeToLiveSeconds
判断
overflowToDisk设定当内存缓存溢出的时候是否将过期的element
缓存到磁盘上
timeToIdleSeconds当缓存在EhCache中的数据前后两次访问的时间超
过timeToIdleSeconds的属性取值时, 这些数据便
会删除,默认值是0,也就是可闲置时间无穷大
timeToLiveSeconds缓存element的有效生命期,默认是0.,也就是
element存活时间无穷大
diskSpoolBufferSizeMBDiskStore(磁盘缓存)的缓存区大小。默认是
30MB。每个Cache都应该有自己的一个缓冲区
diskPersistent在VM重启的时候是否启用磁盘保存EhCache中的数
据,默认是false。
diskExpiryThreadIntervalSeconds磁盘缓存的清理线程运行间隔,默认是120秒。每
个120s, 相应的线程会进行一次EhCache中数据的
清理工作
memoryStoreEvictionPolicy当内存缓存达到最大,有新的element加入的时
候, 移除缓存中element的策略。 默认是LRU (最
近最少使用),可选的有LFU (最不常使用)和
FIFO (先进先出)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值