mybatis-3.4.5.jar
asm-5.1.jar
javassist-3.20.0-GA.jar
log4j-1.2.16.jar
log4j-api-2.8.2.jar
log4j-core-2.8.2.jar
slf4j-api-1.7.7.jar
slf4j-log4j12-1.7.7.jar
mysql-connector-java-5.1.38.jar
junit-4.12.jar
hamcrest-core-1.3.jar
ehcache-core-2.6.11.jar
mybatis-ehcache-1.1.0.jar
Mybatis默认是没有开启二级缓存,在mapper映射文件中,配置cache标签的type为ehcache对cache接口的实现类类型。
1、 在核心配置文件SqlMapConfig.xml中加入以下内容(开启二级缓存总开关):
在settings标签中添加以下内容:
<setting name="cacheEnabled" value="true"/>
2、 在UserMapper映射文件中,加入以下内容,开启二级缓存:
<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 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='丰台区'}