登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

学无止境

一点积累,与大家分享

 
 
 

日志

 
 

试用Hibernate二级缓存Ehcache  

2010-03-25 17:36:36|  分类: java技术 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

from:http://www.javaeye.com/topic/582278

试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. cache.provider_class=org.hibernate.cache.EhCacheProvider   
  2.   
  3. hibernate.cache.use_query_cache=true   

cache.provider_class=org.hibernate.cache.EhCacheProviderhibernate.cache.use_query_cache=true  

 

The following properties are optional, but I recommend that we add them for testing:

 

 

Xml代码 试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. hibernate.generate_statistics=true  
  2.   
  3. hibernate.cache.use_structured_entries=true  
  4.   
  5. show_sql=true   

hibernate.generate_statistics=truehibernate.cache.use_structured_entries=trueshow_sql=true  

 

In particular, property show_sql=true is helpful for tracing cache behavior.  This setting causes Hibernate to display all SQL statements on the system console.

 

试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. <ehcache>  
  2.   
  3.     <defaultCache  
  4.             maxElementsInMemory="10000"  
  5.             eternal="true"  
  6.             overflowToDisk="false"  
  7.             memoryStoreEvictionPolicy="FIFO"  
  8.             />  
  9.   
  10. </ehcache>   

<ehcache> <defaultCache maxElementsInMemory="10000" eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="FIFO" /></ehcache>  

 

This minimal setup will apply the same caching rules to all entities.  Depending on the results of our testing, we may later enhance the ehcache.xml file with one entry for each reference class to be cached to allow granular control 

 

试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. @Entity  
  2. @Table(name = "q_dialog", uniqueConstraints...)   
  3. @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)   
  4. public class Questionnaire extends QuestionBase implements Serializable   

@Entity@Table(name = "q_dialog", uniqueConstraints...)@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)public class Questionnaire extends QuestionBase implements Serializable  

 

Usage CacheConcurrencyStrategy.READ_ONLY should be applied in all cases.  This annotation will cause Hibernate/Ehcache to cache the entity.

 

试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. @OneToMany(cascade = CascadeType.ALL, fetch ...)   
  2. @OrderBy("sequence asc")   
  3. @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)   
  4. public Set<QuestionSetInNaire> getQuestionSetsInNaire()   

@OneToMany(cascade = CascadeType.ALL, fetch ...)@OrderBy("sequence asc")@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)public Set<QuestionSetInNaire> getQuestionSetsInNaire()  

 

This change will cause Ehcache to cache collection Questionnaire questionSetInNaire.

 

试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">  
  2.    <property name="sessionFactory">  
  3.       <ref bean="sessionFactory" />  
  4.    </property>  
  5.    <property name="cacheQueries">  
  6.       <value>true</value>  
  7.    </property>  
  8. </bean>   

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> <property name="cacheQueries"> <value>true</value> </property></bean>  

 

I believe that these specifications will cause the HibernateTemplate class to generate cached Query instances This should effectively enable query caching systemwide. 

 

My knowledge of Spring Framework is limited, so please take this recommendation with a grain of salt.  There are a variety of approaches to solve this problem.  Whichever approach you ultimately use, please verify that Hibernate Query (i.e., QueryImpl) instances are in fact being created with the cacheable property set to true .  You should be able to verify this by single-stepping through the HibernateTemplate with a debugger.

 

试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. #hibernate.dialect =org.hibernate.dialect.OracleDialect   
  2. hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect   
  3. #hibernate.dialect = org.hibernate.dialect.SQLServerDialect   
  4. #hibernate.hbm2ddl.auto = update  
  5. #hibernate.generate_statistics = false  
  6. #hibernate.show_sql =false  
  7.   
  8. hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider   
  9. hibernate.cache.use_query_cache=true  
  10.   
  11. hibernate.generate_statistics=true  
  12. hibernate.show_sql =false  
  13. hibernate.cache.use_structured_entries=true  

#hibernate.dialect =org.hibernate.dialect.OracleDialecthibernate.dialect = org.hibernate.dialect.PostgreSQLDialect#hibernate.dialect = org.hibernate.dialect.SQLServerDialect#hibernate.hbm2ddl.auto = update#hibernate.generate_statistics = false#hibernate.show_sql =falsehibernate.cache.provider_class=org.hibernate.cache.EhCacheProviderhibernate.cache.use_query_cache=truehibernate.generate_statistics=truehibernate.show_sql =falsehibernate.cache.use_structured_entries=true

 2,ehcache.xml

Xml代码 试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect">  
  2.     <!--   
  3.     Mandatory Default Cache configuration. These settings will be applied to caches   
  4.     created programmtically using CacheManager.add(String cacheName).   
  5.   
  6.     The defaultCache has an implicit name "default" which is a reserved cache name.   
  7.     -->  
  8.     <defaultCache maxElementsInMemory="10000" eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="FIFO"/>  
  9. </ehcache>  

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect"> <!-- Mandatory Default Cache configuration. These settings will be applied to caches created programmtically using CacheManager.add(String cacheName). The defaultCache has an implicit name "default" which is a reserved cache name. --> <defaultCache maxElementsInMemory="10000" eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="FIFO"/></ehcache>

 3,model example,Questionnaire.java

Java代码 试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. @NamedQueries( { @NamedQuery(name = "Questionnaire.findMaxRefId", query = "select max(qn.refId) from Questionnaire qn"),   
  2.         @NamedQuery(name = "Questionnaire.findMaxVersionByRefId", query = "select max(qn.version) from Questionnaire qn where qn.refId = :refId") })   
  3. @Entity  
  4. @Table(name = "q_dialog", uniqueConstraints = { @UniqueConstraint(columnNames = { "ID", "VERSION" }) })   
  5. @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)   
  6. public class Questionnaire extends QuestionBase implements Serializable {   
  7. ...............................................   
  8. }  

@NamedQueries( { @NamedQuery(name = "Questionnaire.findMaxRefId", query = "select max(qn.refId) from Questionnaire qn"), @NamedQuery(name = "Questionnaire.findMaxVersionByRefId", query = "select max(qn.version) from Questionnaire qn where qn.refId = :refId") })@Entity@Table(name = "q_dialog", uniqueConstraints = { @UniqueConstraint(columnNames = { "ID", "VERSION" }) })@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)public class Questionnaire extends QuestionBase implements Serializable {...............................................}

 4,Query cache,

    Old:

Java代码 试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. public String getResponseLabel(String value) {   
  2.         List<ResponseEntry> lresponseEntity = this.getHibernateTemplate().find("from ResponseEntry as a");   
  3.         for (int i = 0; i < lresponseEntity.size(); i++) {   
  4.             ResponseEntry r = lresponseEntity.get(i);   
  5.             if (r.getValue().equals(value)) {   
  6.                 return r.getLabel();   
  7.             }   
  8.         }   
  9.         return "";   
  10.     }  

public String getResponseLabel(String value) { List<ResponseEntry> lresponseEntity = this.getHibernateTemplate().find("from ResponseEntry as a"); for (int i = 0; i < lresponseEntity.size(); i++) { ResponseEntry r = lresponseEntity.get(i); if (r.getValue().equals(value)) { return r.getLabel(); } } return ""; }

   New:

Java代码 试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. public String getResponseLabel(String value) {   
  2.         String sql = "from ResponseEntry as a";   
  3.         Query query = this.getSession().createQuery(sql);   
  4.         query.setCacheable(true);   
  5.         List<ResponseEntry> lresponseEntity = query.list();   
  6.         for (int i = 0; i < lresponseEntity.size(); i++) {   
  7.             ResponseEntry r = lresponseEntity.get(i);   
  8.             if (r.getValue().equals(value)) {   
  9.                 return r.getLabel();   
  10.             }   
  11.         }   
  12.         return "";   
  13.     }  

public String getResponseLabel(String value) { String sql = "from ResponseEntry as a"; Query query = this.getSession().createQuery(sql); query.setCacheable(true); List<ResponseEntry> lresponseEntity = query.list(); for (int i = 0; i < lresponseEntity.size(); i++) { ResponseEntry r = lresponseEntity.get(i); if (r.getValue().equals(value)) { return r.getLabel(); } } return ""; }

 5,Depth Optimization

    Old:

Java代码 试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. public DisplayFlagRecord findByPageQuestionAndDialogInstance(QuestionInSet pageQuestion, Dialog dialogInstance) {   
  2.         String hql = "from DisplayFlagRecord where pageQuestion = :pageQuestion and dialogInstance = :dialogInstance";   
  3.         Query query = this.getSession().createQuery(hql);   
  4.         query.setCacheable(true);   
  5.            
  6.            
  7.         List<DisplayFlagRecord> records = query.setEntity("pageQuestion", pageQuestion).setEntity("dialogInstance", dialogInstance).list();   
  8.         if (records != null && records.size()>0) {   
  9.             return records.get(0);   
  10.         }   
  11.         return null;   
  12.     }  

public DisplayFlagRecord findByPageQuestionAndDialogInstance(QuestionInSet pageQuestion, Dialog dialogInstance) { String hql = "from DisplayFlagRecord where pageQuestion = :pageQuestion and dialogInstance = :dialogInstance"; Query query = this.getSession().createQuery(hql); query.setCacheable(true); List<DisplayFlagRecord> records = query.setEntity("pageQuestion", pageQuestion).setEntity("dialogInstance", dialogInstance).list(); if (records != null && records.size()>0) { return records.get(0); } return null; }

    New:

Java代码 试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. public DisplayFlagRecord findByPageQuestionAndDialogInstance(QuestionInSet pageQuestion, Dialog dialogInstance) {   
  2.         Iterator listDisplayFlagRecords = dialogInstance.getDisplayFlagRecords().iterator();   
  3.         while (listDisplayFlagRecords.hasNext()) {   
  4.             DisplayFlagRecord lDisplayFlagRecord = (DisplayFlagRecord) listDisplayFlagRecords.next();   
  5.             if (lDisplayFlagRecord.getPageQuestion() == pageQuestion)   
  6.                 return lDisplayFlagRecord;   
  7.         } // Response could not be found:   
  8.         return null;   
  9. }  

public DisplayFlagRecord findByPageQuestionAndDialogInstance(QuestionInSet pageQuestion, Dialog dialogInstance) { Iterator listDisplayFlagRecords = dialogInstance.getDisplayFlagRecords().iterator(); while (listDisplayFlagRecords.hasNext()) { DisplayFlagRecord lDisplayFlagRecord = (DisplayFlagRecord) listDisplayFlagRecords.next(); if (lDisplayFlagRecord.getPageQuestion() == pageQuestion) return lDisplayFlagRecord; } // Response could not be found: return null;}

Java代码 试用Hibernate二级缓存Ehcache - 积累在于坚持 - 学无止境

  1. private List<Response> findRespose(Long pageInQuestionId, Set aSetResponses,String responseValue) {   
  2.         List<Response> lResponses = new ArrayList();   
  3.         Iterator listResponses = aSetResponses.iterator();   
  4.         while (listResponses.hasNext()) {   
  5.             Response lResponse = (Response) listResponses.next();              
  6.             if (lResponse.getQuestion().getId() == pageInQuestionId && lResponse.getValue().equals(responseValue)){   
  7.                 lResponses.add(lResponse);   
  8.             }   
  9.                     
  10.         } // Response could not be found:   
  11.         return lResponses;   
  12.     }  

  评论这张
 
阅读(682)| 评论(0)

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018