| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
openkk
12年前发布

在Hibernate中使用EhCache

     <p>EhCache是一个纯Java程序,可以在Hibernate中作为一个插件引入。它具有运行速度快、结构简单、占用内存小、很小的依赖性、支持多CPU服务器、文档齐全等特点。</p>    <p>在Hibernate中使用EhCache,需要在hibernate.cfg.xml中设置如下:</p>    <table border="1" cellspacing="0" cellpadding="2" width="400" align="center">     <tbody>      <tr>       <td class="code" bgcolor="#e6e6e6"><pre><property name=” hibernate.cache.provider_class”> org.hibernate.cache.EhCacheProvider </property></pre></td>      </tr>     </tbody>    </table> EhCacheProvider类位于hibernate3.jar包中,而不是位于ehcache-1.1.jar包中。EhCache有自己的配置文档,名为ehcache.xml。在Hibernate3.x中的etc目录下有ehcache.xml的示范文件,将其复制应用程序的src目录下(编译时会把ehcache.xml复制到WEB-INF/classess目录下),对其中的相关值进行更改以和自己的程序相适合。进行配置后,在ehcache.xml文件中的全部代码如下:    <br />    <table border="1" cellspacing="0" cellpadding="2" width="400" align="center">     <tbody>      <tr>       <td class="code" bgcolor="#e6e6e6"><pre>  <diskStore path="d:\\cache"/> //设置cache.data文件的存放位置</pre><pre>    <defaultCache maxElementsInMemory="10000" //缓存中允许创建的最大对象数 eternal="false" //缓存中对象是否为永久的 timeToIdleSeconds="120" //缓存数据钝化时间(即对象在它过期前的空闲时间) timeToLiveSeconds="120" //缓存数据生存时间(即对象在它过期前的生存时间) overflowToDisk="true"  //是否启用磁盘缓存 /></pre><pre>    <cache name="Student"   //用户自定义的Cache配置 maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" /> </ehcache></pre></td>      </tr>     </tbody>    </table>    <p>此外,还需要在持久化类的映射文件中进行配置。例如,Group(班级)和Student(学生)是一对多的关系,它们对应的数据表分别是t_group和t_student。现在要把Student类的数据进行二级缓存,这需要在两个映射文件(Student.hbm.xml和Group.hbm.xml)中都对二级缓存进行配置。</p>    <p>在Group.hbm.xml中配置二级缓存如下:</p>    <table border="1" cellspacing="0" cellpadding="2" width="400" align="center">     <tbody>      <tr>       <td class="code" bgcolor="#e6e6e6"><pre>    …… <hibernate-mapping> <class name="Group" table="t_group" lazy="false"> …… <set name="students" cascade="save-update"  inverse="true"   <!--关系由Student维护--> lazy="true" > <cache usage="read-write"/>  //<!--集合中的数据将被缓存--> <key column="id"/> <one-to-many class="Student"/> </set> </class> </hibernate-mapping> ……</pre></td>      </tr>     </tbody>    </table> 上述文件虽然在<set>标记中设置了<cache usage="read-write"/>,但Hibernate仅把和Group相关的Student的主键id加入到缓存中,如果希望把整个Student的散装属性都加入到二级缓存中,还需要在Student.hbm.xml文件的<class>标记中加入<cache>子标记,如下所示:    <br />    <table border="1" cellspacing="0" cellpadding="2" width="400" align="center">     <tbody>      <tr>       <td class="code" bgcolor="#e6e6e6"><pre><class name="Student" table="t_student" > <cache usage="read-write" /> <!--cache标记需跟在class标记后--> …… </class></pre></td>      </tr>     </tbody>    </table>     
 本文由用户 openkk 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1322893871640.html
Hibernate Ehcache 缓存组件