对spring mybatis 缓存的使用

网上找了很多关于对缓存的描述,说得天花乱坠,不易读懂,自己总结简单几句话对缓存的理解:

一级缓存,可理解为数据对象存储在内存的中,比如在一次操作数据库,会得到一个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" />


其实大可不必,因为默认就是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 , 第二次没有访问数据库。






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值