Mybatis默认是没有开启二级缓存,在mapper映射文件中,配置cache标签的type为ehcache对cache接口的实现类类型。
1、 在核心配置文件SqlMapConfig.xml中加入以下内容(开启二级缓存总开关): 在settings标签中添加以下内容:
<!-- 开启二级缓存总开关 --> <setting name="cacheEnabled" value="true"/>2、 在UserMapper映射文件中,加入以下内容,开启二级缓存:
<!-- 开启本mapper下的namespace的Ehcache二级缓存 --> <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>在classpath下添加ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <!-- 指定数据在磁盘中的存储位置。缓存数据要存放的磁盘地址 --> <diskStore path="E:\ehcache_tmp"/> <!-- defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略 以下属性是必须的: # maxElementsInMemory - 在内存中缓存的element的最大数目 # maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大 # eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断 # overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上 以下属性是可选的: # timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大 # timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大 # diskSpoolBufferSizeMB - 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区. # diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。 # diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作 # memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出) --> <defaultCache maxElementsInMemory="1000" maxElementsOnDisk="10000000" eternal="false" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> </ehcache>此时UserMapper.xml下的sql执行完成会以HashMap的形式存储到它的缓存区域。测试:
@Test public void TestSelect() throws ParseException { UserDao ud = new UserDaoImpl(session); int id = 35; User user1 = ud.findUserById(id); logger.debug(user); UserDao ud2 = new UserDaoImpl(session); EhcacheUtil.getInstance().put("cache", "user" + id, user); User user2 = ud2.findUserById(id); logger.debug(user2); } <!--结果相同的数据只查询了一次数据库,配置成功--> 09:57:47,840 DEBUG findUserById:159 ==> Preparing: SELECT * FROM user WHERE user.id = ? 09:57:47,880 DEBUG findUserById:159 ==> Parameters: 35(Integer) 09:57:47,931 DEBUG findUserById:159 <== Total: 1 09:57:47,932 DEBUG MybatisTest:59 User{id=35, username='张三', birthday=Mon Jan 01 00:00:00 CST 2001, sex='男', address='丰台区'} 缓存命中 09:57:47,939 DEBUG MybatisTest:63 User{id=35, username='张三', birthday=Mon Jan 01 00:00:00 CST 2001, sex='男', address='丰台区'}