缓存机制分为一级缓存和二级缓存
一级缓存机制禁用,在方法内部可以通过session.commit()进行事务提交,也可以在全局配置文件中进行一级缓存禁用/启用,
<!--在Mybatis3.3以后使用localCacheScope属性可以禁用一级缓存
LocalCacheScope=”session” : 设置一级缓存数据保存在当前session中
LocalCacheScope=”statment” 设置当前session不保存任何数据,即禁用一级缓存-->
<setting name="localCacheScope" value="SESSION"/>
还有就是清除一级session缓存,session.clearCacher()方法
@Test
public void cacheTest(){
/*读取全局配置*/
InputStream inputStream= Resources.getResourceAsStream("sqlMapConfig.xml");
/*创建工厂类*/
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
/*获取可执行session*/
SqlSession session=sessionFactory.openSession();
/*By mapper inference come implements session mapping*/
//通过mapper接口实现session映射
EmpMapper empMapper=session.getMapper(EmpMapper.class);
/* call select method*/
EmployeeExt ext = empMapper.selectEmpAndArticlesByEmpId(1);
EmployeeExt ext1 = empMapper.selectEmpAndArticlesByEmpId(1);
System.out.println(ext);
System.out.println(ext1);
session.clearCache();
}
二级缓存类似于一级缓存,只是它与一级缓存用法不同
首先在方法内部是无法禁用/启用二级缓存,可以通过要修改xml中,namespace范围内,添加二级缓存,<cache>标签内,属性值eviction,flushInterval,size,readyOnly。
<!--局部二级缓存-->
<!--eviction环境值,flushInterval刷新间隔,sizeSession大小-->
<cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>
还可以通过全局配置进行操作:
<!-- 开启二级缓存,默认值也是true,但是要显式的配置出来-->
<!--如果是false,则是关闭二级缓存,一级缓存一直开启-->
<setting name="cacheEnabled" value="true"/>