Mybatis 緩存

1. 一級緩存:其存儲做用域爲 Session,當 Session flush 或 close 以後,該Session中的全部 Cache 就將清空。java

2. 二級緩存與一級緩存其機制相同,不一樣在於其存儲做用域爲 Mapper(Namespace),而且可自定義存儲源,如第三方 Ehcache。算法

1、一級緩存sql

實體類city數據庫

public class City implements Serializable{
	private static final long serialVersionUID = 1L;
	private int id;
	private String cityName;
	private String provinceId;
        //getters、setters
}

CityMapper緩存

<mapper namespace="com.area.dao.CityDao">
	<select id="findByProvinceId" resultType="city">
		select * from city where provinceId = #{pId} 
	</select>
</mapper>

測試;session

@Test
public void testById() {
	sqlSession = sqlSessionFactory.openSession();
	CityDao cityDao = sqlSession.getMapper(CityDao.class);
	cityDao.findByProvinceId("p1");
	cityDao.findByProvinceId("p1");
	sqlSession.commit();
}

測試結果mybatis

[com.area.dao.CityDao.findByProvinceId] - ==>  Preparing: select * from city where provinceId = ? 
[com.area.dao.CityDao.findByProvinceId] - ==> Parameters: p1(String)
[com.area.dao.CityDao.findByProvinceId] - <==      Total: 1

從sql中能夠看出,只有一次查詢數據庫的過程,這種現象產生的緣由就是mybatis的一級緩存,而且一級緩存是默認開啓的app

2、二級緩存測試

未開啓二級緩存spa

@Test
public void test() {
	sqlSession = sqlSessionFactory.openSession();
	CityDao cityDao = sqlSession.getMapper(CityDao.class);
	cityDao.findByProvinceId("p1");
	sqlSession.commit();
	sqlSession1 = sqlSessionFactory.openSession();
	CityDao cityDao1 = sqlSession1.getMapper(CityDao.class);
	cityDao1.findByProvinceId("p1");
	sqlSession.commit();
}
2016-11-09 11:45:00 - ==>  Preparing: select * from city where provinceId = ? 
2016-11-09 11:45:00 - ==> Parameters: p1(String)
2016-11-09 11:45:00 - <==      Total: 1
2016-11-09 11:45:00 - JDBC Connection 
2016-11-09 11:45:00 - ==>  Preparing: select * from city where provinceId = ? 
2016-11-09 11:45:00 - ==> Parameters: p1(String)
2016-11-09 11:45:00 - <==      Total: 1
2016-11-09 11:45:00 - Returning JDBC Connection to DataSource

 兩個session,分別查詢provinceid爲p1的city,與數據庫交互了兩次,這樣說明mybatis當前並無開啓二級緩存。

 配置以下:

<settings>
	<setting name="cacheEnabled" value="true" />
</settings>

 

<mapper namespace="com.area.dao.CityDao">
	<select id="findByProvinceId" resultType="city">
		select * from city where provinceId = #{pId} 
	</select>
	<cache/>
</mapper>

測試結果 

2016-11-09 11:41:11 - ==>  Preparing: select * from city where provinceId = ? 
2016-11-09 11:41:11 - ==> Parameters: p1(String)
2016-11-09 11:41:12 - <==      Total: 1
2016-11-09 11:41:12 - Cache Hit Ratio [com.area.dao.CityDao]: 0.5
2016-11-09 11:41:12 - Returning JDBC Connection to DataSource

只發出一條sql,第二條顯示命中緩存,說明二級緩存起到緩存做用 

總結:

mybatis

一級緩存:默認開啓

二級緩存:

1. 映射語句文件中的全部select語句將會被緩存。 

2. 映射語句文件中的全部insert,update和delete語句會刷新緩存。 

3. 緩存會使用Least Recently Used(LRU,最近最少使用的)算法來收回。 

4. 緩存會根據指定的時間間隔來刷新。 

5. 緩存會存儲1024個對象

相關文章
相關標籤/搜索