浅析Hibernate使用EhCache

学习Hibernate时,经常会遇到Hibernate使用EhCache问题,这里将介绍Hibernate使用EhCache问题的解决方法。

在Hibernate使用EhCache

EhCache是一个纯JAVA程序,可以在Hibernate中作为一个插件引入。在Hibernate使用EhCache需要在Hibernate的配置文件中设置如下:

 
 
 
  1. <propery name="hibernate.cache.provider_class"> 
  2. org.hibernate.cache.EhCacheProvider  
  3. </property> 
  4. <ehcache> 
  5. <diskStore path="c:\\cache"/>
  6. //设置cache.data文件存放位置  
  7.  
  8. <defaultCache 
  9. maxElementsInMemory="10000" 
  10. //缓存中允许创建的最大对象数  
  11. eternal="false"
  12. //缓存中对象是否为永久的  
  13. timeToIdleSeconds="120"
  14. //缓存数据钝化时间(即对象在它过期前的空闲时间)  
  15. timeToLiveSeconds="120"
  16. //缓存数据生存时间(即对象在它过期前的生存时间)  
  17. overflowToDisk="true" 
  18. /> 
  19.  
  20. <cache name="Student"
  21. //用户自定义的Cache配置  
  22. maxElementsInMemory="10000" 
  23. eternal="false" 
  24. timeToIdleSeconds="300" 
  25. timeToLiveSeconds="600" 
  26. overflowToDisk="true" 
  27. /> 
  28. </ehcache> 

此外我们还需要在持久化类的映射文件中进行配置。例如,Group(班级)和Student(学生)是一对多的关系,它们对应的数据表分别是t_group和t_student.现在要把Student类的数据进行二级缓存,这需要在二个映射文件中都对二级缓存进行配置。

在Group.hbm.xml中如下,在其<set></set>中添加

<cache usage="read-write"/><!——集合中的数据被缓存——>上述文件虽然在<set>标记中设置了& lt;cache usage="read-write"/>,但Hibernate只是把Group相关的Student的主键ID加入到缓存中,如果希望把整个 Student的散装属性都加入到二级缓存中,还需要在Student.hbm.xml文件的<class>标记中添加<cache>子标记。如下:

 
 
 
  1. <class name="Student" table="t_student"> 
  2. <cache usage="read-write" /><!--cache标记需跟在class标记后--> 
  3. </class> 

【编辑推荐】

  1. Hibernate3.1简单描述
  2. Hibernate save基础简介
  3. 浅析Hibernate 3二级缓存基础
  4. Hibernate流行架构浅析
  5. Hibernate update浅谈
THE END