MyBatis的EhCache框架

首先在resource里面增加一个ehcache.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http:www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"
    monitoring="autodetect" dynamicConfig="true">
    <diskStore path="c:/cache" />
    <defaultCache maxElementsInMemory="3000" eternal="false"
        copyOnRead="true" copyOnWrite="true" timeToIdleSeconds="3600"
        timeToLiveSeconds="3600" overflowToDisk="true" diskPersistent="true" />
    <!-- copyOnRead从缓存中读取数据是返回对象的引用还是复制一个对象返回,默认是false, copyOnWrite意思是判断写入缓存时是直接混村对象的引用还是复制一个对象然后缓存,默认是false -->
    
    <cache name="marc.mybatis.lesson1.mapper.SysRoleMapper" maxElementsInMemory="3000" eternal="false"
        copyOnRead="true" copyOnWrite="true" timeToIdleSeconds="3600"
        timeToLiveSeconds="3600" overflowToDisk="true" diskPersistent="true" />
</ehcache>

注意cache配置一个是默认配置, 一个是针对namespace的配置.

mapper的xml文件修改指向ehcache

<mapper namespace="marc.mybatis.lesson1.mapper.SysRoleMapper">
    <!-- <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="false" 
        /> -->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache" />

这就完成了, 运行之前的测试, 输出是一样的, 二级缓存生效了.

这里再次强调, 为避免脏数据产生, 在一个namespace里面, 最好只有单纯的select, 也就是查询, 而别混有很多的删, 改, 增.

原文地址:https://www.cnblogs.com/Montauk/p/9797518.html