MyBaits缓存机制
来源:互联网 发布:淘宝拍立淘不能用了 编辑:程序博客网 时间:2024/06/11 02:35
1、一级缓存(SqlSession)
一级缓存的作用域是同一个SqlSession,在同一个sqlSession中两次执行相同的sql语句,第一次执行完毕会将数据库中查询的数据写到缓存(内存),第二次会从缓存中获取数据将不再从数据库查询,从而提高查询效率。当一个sqlSession结束后该sqlSession中的一级缓存也就不存在了。若sqlSession执行了commit操作(insert、update、delete),会清空缓存,避免读脏数据,存储最新的信息。Mybatis默认开启一级缓存。
当spring和mybaits整合后,事务掌握在service中,若执行两次查询相同的信息,不走一级缓存,因为service结束后,sqlSession就关闭,一级缓存就清空。
2、二级缓存(Mapper)
二级缓存是mapper级别的缓存,多个SqlSession去操作同一个Mapper的sql语句,多个SqlSession去操作数据库得到数据会存在二级缓存区域,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的。二级缓存是多个SqlSession共享的,其作用域是mapper的同一个namespace,不同的sqlSession两次执行相同namespace下的sql语句且向sql中传递参数也相同即最终执行相同的sql语句,第一次执行完毕会将数据库中查询的数据写到缓存(内存),第二次会从缓存中获取数据将不再从数据库查询,从而提高查询效率。但是mybatis默认开启的二级缓存默认实现类是一个内存级别的,不建议使用,所以我们要配置第三方缓存框架ehcache:
porm.xml
<!-- ehcache --><dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.1</version></dependency><!-- mybatis-ehcache --><dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.0</version></dependency>
在Configuration.xml文件中加入
<setting name="cacheEnabled" value="true"/>
在对应的Mapper.xml中加入
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
新建ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <diskStore path="C:\cache"/> <defaultCache maxElementsInMemory="3000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="100" memoryStoreEvictionPolicy="LRU" /> <cache name="userCache" maxElementsInMemory="3000" eternal="false" overflowToDisk="true" timeToIdleSeconds="3600" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" /> </ehcache>
3、刷新缓存
在mapper的同一个namespace中,如果有其它insert、update、delete操作数据后需要刷新缓存,如果不执行刷新缓存会脏读数据。
设置statement配置中flushCache属性,默认为true即刷新缓存,如果改成false则不会刷新。使用缓存时如果手动修改数据库表中的查询数据会出现脏读。
参考:http://www.360doc.com/content/15/1205/07/29475794_518018352.shtml
- Mybaits缓存机制分析
- MyBaits缓存机制
- 关于mybaits的缓存
- MyBaits缓存原理(源码级跟踪)
- mybaits中的一级缓存和二级缓存使用
- MyBaits
- MyBaits
- Mybaits
- Mybaits
- mybaits
- mybaits
- 缓存机制
- 缓存机制
- 缓存机制
- 缓存机制
- 缓存机制
- 缓存机制
- 缓存机制
- 【caffe-windows】 caffe-master 之 cifar10 超详细
- Android自动化测试之Monkey(二)
- 《PCL点云库学习&VS2010(X64)》Part 21 VTK6.2+VS2013 利用PCL读取ply格式网格曲面
- Box2D v2.3.0 用户指南(第一章)
- urllineedit.h
- MyBaits缓存机制
- BZOJ1070: [SCOI2007]修车
- springBoot与MyBatis整合示例
- urllineedit.cpp
- 程序员面试金典: 9.5位操作 5.5编写一个函数,确定需要改变几个位,才能将整数A转成整数B
- Vigenere密码加密解密原理
- Box2D v2.3.0 用户指南(第二章)
- openresty学习网址
- Latex:简介及安装