网上找了很多关于对缓存的描述,说得天花乱坠,不易读懂,自己总结简单几句话对缓存的理解:
第一次与第二次的参数完全相同,so , 第二次没有访问数据库。
一级缓存,可理解为数据对象存储在内存的中,比如在一次操作数据库,会得到一个session, 在这个session 没有没 commit 或者 close 之前,若参数相同,是不用再次访问数据库,数据直接从缓存中获取,当session commit 之后, 缓存将会被clear 掉。
二级缓存,大致与一级缓存相同,区别在于二级缓存存储的地方不是内存,可以理解为硬盘上,这时,二级缓存的数据将不受session 的影响,因为数据被序列化之后存储在了本地,因此如果要用到二级缓存,object 必须被序列化 实现 Serializable 接口。
By the way, spring 整合了mybatis 之后,是不能使用一级缓存的,上面说了,要想获得一级缓存中的数据,必须在session 没有被commit 或者close 之前,而整合了spring 之后,每次读写完毕session 会自动commit.
如何配置
1. 在项目中添加如下jar 包(版本不限):
mybatis-ehcache.jar
ehcache-core.jar
2.在Mapper.xml 里面添加
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
完了,仅此而已,在其他网站上还有建议在 mybatis 核心文件里面添加
<setting name="cacheEnabled" value="true" />
接下来可以试着写个test, 访问数据库,多次访问用同样的参数,你会发现log 只打印了一次,如下代码:
log.info("sqlSessionTemplate : "+ sqlSessionTemplate);
log.info("--------1------");
AlarmTO alarmTO = sqlSessionTemplate.getMapper(AlarmMapper.class).getAlarm("al.1429687964378.156304");
log.info("-------2-------");
AlarmTO alarmTO1 = sqlSessionTemplate.getMapper(AlarmMapper.class).getAlarm("al.1429687964378.156304");
log.info("-------3-------");
AlarmTO alarmTO2 = sqlSessionTemplate.getMapper(AlarmMapper.class).getAlarm("al.1429717085776.111995");
log 如下:
[10-14 15:03:54 661] [INFO com.mybiats.MybiatsTest] sqlSessionTemplate : org.mybatis.spring.SqlSessionTemplate@371fac61
[10-14 15:03:54 661] [INFO com.mybiats.MybiatsTest] --------1------
[10-14 15:03:54 834] [DEBUG com.mapper.AlarmMapper.getAlarm] ooo Using Connection [com.mysql.jdbc.JDBC4Connection@37cbcec3]
[10-14 15:03:54 850] [DEBUG com.mapper.AlarmMapper.getAlarm] ==> Preparing: select ID,AlarmType,Owner from alarm where id = ?
[10-14 15:03:54 881] [DEBUG com.mapper.AlarmMapper.getAlarm] ==> Parameters: al.1429687964378.156304(String)
[10-14 15:03:54 896] [DEBUG com.mapper.AlarmMapper.getAlarm] <== Total: 1
[10-14 15:03:54 912] [INFO com.mybiats.MybiatsTest] -------2-------
[10-14 15:03:54 912] [INFO com.mybiats.MybiatsTest] -------3-------
[10-14 15:03:54 943] [DEBUG com.mapper.AlarmMapper.getAlarm] ooo Using Connection [com.mysql.jdbc.JDBC4Connection@66aac993]
[10-14 15:03:54 943] [DEBUG com.mapper.AlarmMapper.getAlarm] ==> Preparing: select ID,AlarmType,Owner from alarm where id = ?
[10-14 15:03:54 943] [DEBUG com.mapper.AlarmMapper.getAlarm] ==> Parameters: al.1429717085776.111995(String)
[10-14 15:03:54 943] [DEBUG com.mapper.AlarmMapper.getAlarm] <== Total: 1
第一次与第二次的参数完全相同,so , 第二次没有访问数据库。