在Hibernate使用EhCache
EhCache是一个纯JAVA程序,可以在Hibernate中作为一个插件引入。在Hibernate使用EhCache需要在Hibernate的配置文件中设置如下:
<propery name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>
<ehcache>
<diskStore path="c:\\cache"/>
//设置cache.data文件存放位置
<defaultCache
maxElementsInMemory="10000"
//缓存中允许创建的最大对象数
eternal="false"
//缓存中对象是否为永久的
timeToIdleSeconds="120"
//缓存数据钝化时间(即对象在它过期前的空闲时间)
timeToLiveSeconds="120"
//缓存数据生存时间(即对象在它过期前的生存时间)
overflowToDisk="true"
/>
<cache name="Student"
//用户自定义的Cache配置
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
</ehcache>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
此外我们还需要在持久化类的映射文件中进行配置。例如,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>子标记。如下:
<class name="Student" table="t_student">
<cache usage="read-write" /><!--cache标记需跟在class标记后-->
</class>
- 1.
- 2.
- 3.
【编辑推荐】