Mybatis07

    科技2022-07-10  83

    Mybatis07_缓存

    1. 缓存分类:2. 开启Mybatis自带的二级缓存:3. 使用 ehcache 的二级缓存:


    1. 缓存分类:

    一级缓存:sqlSession级别,默认开启,不能关闭。

    在同一sqlSession范围内,执行两次相同的sql查询语句时,第一次执行的结果会保存至缓存,第二次查询将直接从缓存中获取。

    当sqlSession执行了更新操作时,Mybatis将清空缓存。

    二级缓存:Mapper级别,默认关闭,可以开启。

    二级缓存中,多个sqlSession使用同一个Mapper的SQL语句操作数据库,查询结果会存在二级缓存区。

    二级缓存是多个sqlSession共享的,其作用域是Mapper的同一个namespace


    2. 开启Mybatis自带的二级缓存:
    step1: 开启二级缓存 <settings> <setting name="cacheEnabled" value="true"/> </settings> step2: 在mapper.xml中添加配置 <cache></cache> step3: 对应的实体类实现序列化接口 public class Account implements Serializable { }
    3. 使用 ehcache 的二级缓存:
    step1: 导入 ehcache 的依赖 <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.4.3</version> </dependency> step2: 添加 ehcache.xml 配置文件 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore/> <defaultCache maxElementsInMemory="1000" maxElementsOnDisk="10000000" eternal="false" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> </ehcache> step3: 开启二级缓存 <settings> <setting name="cacheEnabled" value="true"/> </settings> step4: 在mapper.xml中添加配置 <cache type="org.mybatis.caches.ehcache.EhcacheCache"> <!-- 缓存创建之后,最后⼀次访问缓存的时间⾄缓存失效的时间间隔,单位为s --> <property name="timeToIdleSeconds" value="3600"/> <!-- 缓存⾃创建时间起⾄失效的时间间隔,单位为s --> <property name="timeToLiveSeconds" value="3600"/> <!-- 缓存回收策略,LRU表示移除近期使⽤最少的对象 --> <property name="memoryStoreEvictionPolicy" value="LRU"/> </cache>

    注:使用 ehcache 的二级缓存,实体类无需实现序列化接口

    Processed: 0.015, SQL: 8