一級緩存java
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方法也會清空緩存sql
二級緩存數據庫
對應的bean實例須要實現Serializable接口,實例必須是可序列化的緩存
須要在對於的xml文件裏面配置<cache/>mybatis
config.xml文件setting標籤中使用cacheEnabled value 設置爲true(默認開啓)app
select標籤 加上 useCache="true"(默認開啓)ui
若是使用註解方式,在Dao的類名上添加@CacheNamespace (blocking=true)註解spa
properties文件中添加配置開啓sql日誌 logging.level.com.example.demo=debugdebug
啓動項目,執行查詢操做,日誌中只顯示一次查詢記錄日誌
[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