Mybatis一级缓存 是SqlSession级别
1. 不同的sqlSession的相同查询是没有走缓存的
2. 相同的sqlSession的查询如果查询条件不同或期间进行过写操作也是不走缓存的
Mybatis二级缓存 是SqlSessionFactory级别
1.同一个SqlSeesionFactory创建的SqlSession查询结果会被缓存,此后再次执行相同的查询语 句,就会从缓存中获取,与一级缓存的区别是,只要是从同一个工厂生产出来的sqlSeesion就可以走缓存
二级缓存生效条件
(1)在核心配置文件设置全局属性cacheEnable="true",默认是true
(2) 在映射文件中设置标签<cache/>
(3) 数据转换的实体类必须实现序列化接口
(4)要二级缓存生效,还需在最后关闭sqlSession.close() 或提交后才生效
Mybatis缓存查询顺序
二级缓存(大) --> 一级缓存(小)---->数据库---close()--->一级缓存数据写入二级缓存
@Test
public void mybatisTest() {
InputStream inputStream = null;
SqlSession sqlSession = null;
SpuInfoEntity spuInfoEntity = new SpuInfoEntity()
.setSpuName("test")
.setBrandId(243656757L)
.setPublishStatus(1)
.setCreateTime(new Date())
.setUpdateTime(new Date());
//JDBC过程
try {
//获取连接信息
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = factory.openSession(true);
SpuInfoMapper spuInfoMapper = sqlSession.getMapper(SpuInfoMapper.class);
spuInfoMapper.insert(spuInfoEntity);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}