一级缓存
public static SqlSession getSqlSession() { String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession; }
创建一个SqlSession对象,通过这个对象执行数据库操作,调用clearCache,close 方法会清空Cache缓存,执行insert,update,delete方法也会清空缓存
二级缓存
对应的bean实例需要实现Serializable接口,实例必须是可序列化的
需要在对于的xml文件里面配置<cache/>
config.xml文件setting标签中使用cacheEnabled value 设置为true(默认开启)
select标签 加上 useCache="true"(默认开启)
如果使用注解方式,在Dao的类名上添加@CacheNamespace (blocking=true)注解
properties文件中添加配置开启sql日志 logging.level.com.example.demo=debug
启动项目,执行查询操作,日志中只显示一次查询记录
[nio-8079-exec-1] com.example.demo.mapper.CategoryMapper : Cache Hit Ratio [com.example.demo.mapper.CategoryMapper]: 0.0
[nio-8079-exec-1] c.e.d.m.CategoryMapper.getAllCategories : ==> Preparing: select * from category
[nio-8079-exec-1] c.e.d.m.CategoryMapper.getAllCategories : ==> Parameters:
[nio-8079-exec-1] c.e.d.m.CategoryMapper.getAllCategories : <== Total: 2
[nio-8079-exec-2] com.example.demo.mapper.CategoryMapper : Cache Hit Ratio [com.example.demo.mapper.CategoryMapper]: 0.5