MyBatis 默认开启了一级缓存,一级缓存是在SqlSession 层面进行缓存的。即,同一个SqlSession ,屡次调用同一个Mapper和同一个方法的同一个参数,只会进行一次数据库查询,而后把数据缓存到缓冲中,之后直接先从缓存中取出数据,不会直接去查数据库。java
可是不一样的SqlSession对象,由于不用的SqlSession都是相互隔离的,因此相同的Mapper、参数和方法,他仍是会再次发送到SQL到数据库去执行,返回结果。mysql
public static void main(String[] args) { // 自定义的单例SqlSessionFactory模式 SqlSessionFactory factory = SqlSessionFactoryUtil.openSqlSession(); // 得到SqlSession对象 SqlSession sqlSession = factory.openSession(); // 得到dao实体 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 进行两次相同的查询操做 userMapper.selectByPrimaryKey(1); userMapper.selectByPrimaryKey(1); // 注意,当咱们使用二级缓存时候,sqlSession须要使用commit时候才会生效 sqlSession.commit(); System.out.println("\n\n============================================================="); // 得到一个新的SqlSession 对象 SqlSession sqlSession1 = factory.openSession(); // 进行相同的查询操做 sqlSession1.getMapper(UserMapper.class).selectByPrimaryKey(1); // 注意,当咱们使用二级缓存时候,sqlSession须要使用commit时候才会生效 sqlSession.commit(); }
日志输出算法
DEBUG [main] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@77caeb3e] DEBUG [main] - ==> Preparing: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? DEBUG [main] - ==> Parameters: 1(Integer) TRACE [main] - <== Columns: user_ID, login_name, user_name, user_code, user_type, user_active, organization_ID, user_position, password TRACE [main] - <== Row: 1, ASH-001, 小明, JIKF-001, ADMIN, 1, 0, 销售员, 1212121212121 DEBUG [main] - <== Total: 1 ============================================================= DEBUG [main] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@553f17c] DEBUG [main] - ==> Preparing: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? DEBUG [main] - ==> Parameters: 1(Integer) TRACE [main] - <== Columns: user_ID, login_name, user_name, user_code, user_type, user_active, organization_ID, user_position, password TRACE [main] - <== Row: 1, ASH-001, 小明, JIKF-001, ADMIN, 1, 0, 销售员, 1212121212121 DEBUG [main] - <== Total: 1
能够发现,第一次的两个相同操做,只执行了一次数据库。后来的那个操做又进行了数据库查询。sql
为了克服这个问题,须要开启二级缓存,是的缓存zaiSqlSessionFactory层面给各个SqlSession 对象共享。默认二级缓存是不开启的,须要手动进行配置。数据库
<cache/>
若是这样配置的话,不少其余的配置就会被默认进行,如:apache
添加后日志打印以下,能够发现全部过程只使用了一次数据库查询缓存
EBUG [main] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@5622fdf] DEBUG [main] - ==> Preparing: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? DEBUG [main] - ==> Parameters: 1(Integer) TRACE [main] - <== Columns: user_ID, login_name, user_name, user_code, user_type, user_active, organization_ID, user_position, password TRACE [main] - <== Row: 1, AS-01, 小明, HJ-009, ADMIN, 1, 0, 销售员, dasfasdfasdfsdf DEBUG [main] - <== Total: 1 =============================================================
能够在开启二级缓存时候,手动配置一些属性安全
<cache eviction="LRU" flushInterval="100000" size="1024" readOnly="true"/>
各个属性意义以下:并发
能够在Mapper的具体方法下设置对二级缓存的访问意愿:app
useCache配置
若是一条语句每次都须要最新的数据,就意味着每次都须要从数据库中查询数据,能够把这个属性设置为false,如:
<select id="selectAll" resultMap="BaseResultMap" useCache="false">
刷新缓存(就是清空缓存)
二级缓存默认会在insert、update、delete操做后刷新缓存,能够手动配置不更新缓存,以下:
<update id="updateById" parameterType="User" flushCache="false" />
自定义缓存对象,该对象必须实现 org.apache.ibatis.cache.Cache 接口,以下:
import org.apache.ibatis.cache.Cache; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Created by Luky on 2017/10/14. */ public class BatisCache implements Cache { private ReadWriteLock lock = new ReentrantReadWriteLock(); private ConcurrentHashMap<Object,Object> cache = new ConcurrentHashMap<Object, Object>(); private String id; public BatisCache(){ System.out.println("初始化-1!"); } //必须有该构造函数 public BatisCache(String id){ System.out.println("初始化-2!"); this.id = id; } // 获取缓存编号 public String getId() { System.out.println("获得ID:" + id); return id; } //获取缓存对象的大小 public int getSize() { System.out.println("获取缓存大小!"); return 0; } // 保存key值缓存对象 public void putObject(Object key, Object value) { System.out.println("往缓存中添加元素:key=" + key+",value=" + value); cache.put(key,value); } //经过KEY public Object getObject(Object key) { System.out.println("经过kEY获取值:" + key); System.out.println("OVER"); System.out.println("======================================================="); System.out.println("值为:" + cache.get(key)); System.out.println("=====================OVER=============================="); return cache.get(key); } // 经过key删除缓存对象 public Object removeObject(Object key) { System.out.println("移除缓存对象:" + key); return null; } // 清空缓存 public void clear() { System.out.println("清除缓存!"); cache.clear(); } // 获取缓存的读写锁 public ReadWriteLock getReadWriteLock() { System.out.println("获取锁对象!!!"); return lock; } }
在Mapper文件里配置使用该自定义的缓存对象,如:
<cache type="com.sanyue.utils.BatisCache"/>
测试以下:
public static void main(String[] args) { SqlSessionFactory factory = SqlSessionFactoryUtil.openSqlSession(); // 得到SqlSession对象 SqlSession sqlSession = factory.openSession(); // 得到dao实体 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 进行两次相同的查询操做 userMapper.selectByPrimaryKey(1); userMapper.selectByPrimaryKey(1); // 注意,当咱们使用二级缓存时候,sqlSession须要使用commit时候才会生效 sqlSession.commit(); System.out.println("\n\n============================================================="); // 得到一个新的SqlSession 对象 SqlSession sqlSession1 = factory.openSession(); // 进行相同的查询操做 sqlSession1.getMapper(UserMapper.class).selectByPrimaryKey(1); sqlSession1.commit(); }
日志输出以下:
初始化-2! 获得ID:com.sanyue.dao.UserMapper 获取锁对象!!! 经过kEY获取值:151355725:1423317450:com.sanyue.dao.UserMapper.selectByPrimaryKey:0:2147483647: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? :1 OVER ======================================================= 值为:null =====================OVER============================== 获取锁对象!!! 获取锁对象!!! 经过kEY获取值:151355725:1423317450:com.sanyue.dao.UserMapper.selectByPrimaryKey:0:2147483647: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? :1 OVER ======================================================= 值为:null =====================OVER============================== 获取锁对象!!! 获取锁对象!!! 往缓存中添加元素:key=151355725:1423317450:com.sanyue.dao.UserMapper.selectByPrimaryKey:0:2147483647: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? :1,value=[User{userId=1, loginName='AS-01', password='12121212121', userName='小明', userCode='JSD-009', userType='ADMIN', userActive=true, userPosition='销售员'}] 获取锁对象!!! ============================================================= 获取锁对象!!! 经过kEY获取值:151355725:1423317450:com.sanyue.dao.UserMapper.selectByPrimaryKey:0:2147483647: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? :1 OVER ======================================================= 值为:[User{userId=1, loginName='AS-01', password='12121212121', userName='小明', userCode='JSD-009', userType='ADMIN', userActive=true, userPosition='销售员'}] =====================OVER============================== 获取锁对象!!!
能够看出,每次查询数据库前,MyBatis都会先在缓存中查找是否有该缓存对象。只有当调用了commit() 方法,MyBatis才会往缓存中写入数据,数据记录的键为 数字编号+Mapper名+方法名+SQL语句+参数
格式,值为返回的对象值。