使用Hibernate的Query cache
老實(shí)說(shuō), 要做到在JDBC查詢之前決定哪些數(shù)據(jù)需要從JDBC來(lái)還是CACHE來(lái)不是件容易事. 但是HIBERNATE還是很好地完成了這個(gè)任務(wù). QueryCache用來(lái)緩存查詢語(yǔ)句, 及查詢結(jié)果集中對(duì)象的Identifier與Type. 當(dāng)再次使用已緩存的Query時(shí), 就可以通過(guò)對(duì)象的Identifier與Type在SECOND LEVEL CACHE中查找實(shí)際的對(duì)象.
使用hibernate中的QueryCache時(shí)需要在hibernate配置文件中設(shè)置如下屬性:
- < property name="cache.provider_class">
- org.hibernate.cache.HashtableCacheProvider
- < /property>
- < property name="hibernate.cache.use_query_cache">true< /property>
建立ehcache的配置文件ehcache.xml放在classpath下
- < ehcache>
- < diskStore path="java.io.tmpdir"/>
- < defaultCache
- maxElementsInMemory="10000"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- overflowToDisk="true"
- />
- < cache name="com.fhway.hibernate.bean.Employee"
- maxElementsInMemory="10"
- eternal="false"
- timeToIdleSeconds="100"
- timeToLiveSeconds="100"
- overflowToDisk="false"
- />
- < cache name="com.fhway.hibernate.bean.Department"
- maxElementsInMemory="10"
- eternal="false"
- timeToIdleSeconds="100"
- timeToLiveSeconds="100"
- overflowToDisk="false"
- />
- < /ehcache>
在配置文件里面要加入< cache>
如
- < class name="com.fhway.hibernate.bean.Employee " table=" Employee ">
- < cache usage="read-only"/>
可以設(shè)定的策略包括read-only、read-write、nonstrict-read-write與transactional,并不是每一個(gè)第三方快取實(shí)現(xiàn)都支持所有的選項(xiàng),每一個(gè)選項(xiàng)的使用時(shí)機(jī)與支持的產(chǎn)品,可以直接參考Hibernate官方參考快冊(cè)的 20.2.The Second Level Cache;
在程序中需要為Query對(duì)象設(shè)置Cachable屬性:
- Query query = sess.createQuery("from Employee as employee");
- query.setCacheable(true);
- List employees = (List) query.list();
- Iterator iterator = employees.iterator();
- while(iterator.hasNext()){
- System.out.println((Employee) iterator.next());
- }
- Query query1 = sess.createQuery("from Employee as employee");
- query1.setCacheable(true);
- List employees1 = (List) query1.list();
- Iterator iterator1 = employee1.iterator();
- while(iterator1.hasNext()){
- System.out.println((Employee) iterator1.next());
- }
- Employee goncha = (Employee) sess.load(Employee.class, "001");
- System.out.println(goncha);
當(dāng)你調(diào)用以上代碼時(shí)你會(huì)發(fā)現(xiàn)這樣的輸出:
- Hibernate: select employee0_.ID as ID, employee0_.NAME as NAME0_, employee0_.DEPNO0 as DEPNO0_ from AFLYER.EMPLOYEE employee0_
- com.fhway.hibernate.bean.Employee@e020c9
- com.fhway.hibernate.bean.Employee@117f31e
- com.fhway.hibernate.bean.Employee@bad8a8
- com.fhway.hibernate.bean.Employee@104c575
- com.fhway.hibernate.bean.Employee@e020c9
- com.fhway.hibernate.bean.Employee@117f31e
- com.fhway.hibernate.bean.Employee@bad8a8
- com.fhway.hibernate.bean.Employee@104c575
- com.fhway.hibernate.bean.Employee@e020c9
很顯然 該緩存的利用方式對(duì)Query和load()方式有效!
Query上有l(wèi)ist()與iterator()方法,兩者的差別在于list()方法在讀取數(shù)據(jù)時(shí),并不會(huì)利用到快取,而是直接再向數(shù)據(jù)庫(kù)查詢,而iterator()則將讀取到的數(shù)據(jù)寫到快取,并于讀取時(shí)再次利用。(Blob 不能使用cache)
【編輯推薦】