hibernate的session提供了一級(jí)緩存,在同一個(gè)session中對(duì)同一個(gè)id的對(duì)象load兩次,并不會(huì)發(fā)送兩條sql給數(shù)據(jù)庫(kù)。但是session關(guān)閉的時(shí)候,一級(jí)緩存就失效了。
二級(jí)緩存是SessionFactory級(jí)別的全局緩存,它底下可以使用不同的緩存類庫(kù),比如ehcache、oscache等,需要使用緩存實(shí)現(xiàn)方案。
詳細(xì)請(qǐng)看: hibernate二級(jí)緩存攻略
3.1 基本設(shè)置
1. 如果需要特別設(shè)置ehcache的屬性,把一個(gè)ehcache.xml 定義文件拷貝到class-path.
2. jdbc.properties加上
hibernate.cache.use_query_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
3. applicationContext.xml的 <property name="hibernateProperties">下加上
<prop key="hibernate.cache.use_query_cache">$ {hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.provider_class">$ {hibernate.cache.provider_class}</prop>
3.2 Entity級(jí)二級(jí)緩存
Entity二級(jí)緩存是把PO放進(jìn)cache,緩存的key就是ID,value是POJO,不同于查詢的緩存。
Entity二級(jí)緩存在BookDao.get(3),和book.getCategory()的情況下都能用到,把category這樣的小表完全cache到內(nèi)存挺不錯(cuò)的。
在hbm文件中:
<class name="Product" table="PRODUCT" dynamic-insert="true" dynamic-update="true"> <cache usage="nonstrict-read-write"/> <id name="id" column="ID"> <generator class="native"/> </id>
如果你使用的二級(jí)緩存實(shí)現(xiàn)是ehcache的話,需要配置ehcache.xml ,否則就會(huì)使用ehcache默認(rèn)的配置
<cache name="com.xxx.pojo.Foo" maxElementsInMemory="500" eternal="false" timeToLiveSeconds="7200" timeToIdleSeconds="3600" overflowToDisk="true" />
3.3 查詢緩存
上面的二級(jí)緩存是針對(duì)單個(gè)對(duì)象的,如果要對(duì)查詢結(jié)果,則是用下面的語句
query.setCacheable(true);//激活查詢緩存 query.setCacheRegion("myCacheRegion");//指定要使用的cacheRegion,可選
cacheRegion是可選的,可以對(duì)使用的緩存進(jìn)行特殊設(shè)置, 在ehcahe.xml里要補(bǔ)上下面的一段。
<cache name="myCacheRegion" maxElementsInMemory="10" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" />