﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-流星的传说-文章分类-Hibernate</title><link>http://www.blogjava.net/goldstar/category/43019.html</link><description>哥只是个传说</description><language>zh-cn</language><lastBuildDate>Thu, 10 Dec 2009 14:26:59 GMT</lastBuildDate><pubDate>Thu, 10 Dec 2009 14:26:59 GMT</pubDate><ttl>60</ttl><item><title>hibernate 二级缓存入门例子</title><link>http://www.blogjava.net/goldstar/articles/305408.html</link><dc:creator>天外流星</dc:creator><author>天外流星</author><pubDate>Thu, 10 Dec 2009 05:16:00 GMT</pubDate><guid>http://www.blogjava.net/goldstar/articles/305408.html</guid><wfw:comment>http://www.blogjava.net/goldstar/comments/305408.html</wfw:comment><comments>http://www.blogjava.net/goldstar/articles/305408.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/goldstar/comments/commentRss/305408.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/goldstar/services/trackbacks/305408.html</trackback:ping><description><![CDATA[<div class="postbody">配置一：<br />
hibernate.cfg.xml文件中增加<br />
&lt;!--开启二级缓存--&gt;<br />
&lt;property name="cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/property&gt;&nbsp;&nbsp; <br />
<br />
&lt;property name="hibernate.cache.use_query_cache"&gt;true&lt;/property&gt;<br />
配置二：<br />
工程项目src文件下新建一个ehcache.xml文件，其内容为<br />
&lt;!--开启二级缓存--&gt;<br />
&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br />
&lt;ehcache&gt;<br />
&lt;diskStore path="java.io.tmpdir" /&gt;<br />
&lt;defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="180" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /&gt;<br />
<br />
&lt;/ehcache&gt;<br />
配置三：<br />
为了缓存某类的对象，其hbm文件中需添加&lt;cache usage="read-only"/&gt;属性例如：<br />
&lt;?xml version="1.0"?&gt;<br />
&lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"<br />
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;<br />
&lt;!-- <br />
&nbsp;&nbsp;&nbsp; Mapping file autogenerated by MyEclipse - Hibernate Tools<br />
--&gt;<br />
&lt;hibernate-mapping&gt;<br />
<br />
&nbsp;&nbsp; &lt;class name="com.vogue.bbsphoto.entity.Forum" <br />
&nbsp;&nbsp; table="cdb_forums"&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;cache usage="read-only"/&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;id name="ID" column="fid" unsaved-value="null"&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;generator class="increment" /&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/id&gt;<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="name" column="name" type="string" /&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="type" column="type" type="string" /&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/class&gt;<br />
&lt;/hibernate-mapping&gt;<br />
配置四：<br />
为了使用查询缓存，Query必须设置cacheable为true,query.setCacheable(true);<br />
例如dao父类中用于hql查询的方法修改后为：<br />
/**<br />
&nbsp;&nbsp;&nbsp;&nbsp; * 执行hql语句的查询<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @param sql<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @return<br />
&nbsp;&nbsp;&nbsp;&nbsp; */<br />
&nbsp;&nbsp; public List executeQuery(String hql){<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; List list = new ArrayList();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Session session = HibernateSessionFactory.currentSession();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Transaction tx = null;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Query query = session.createQuery(hql);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; query.setCacheable(true);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; tx = session.beginTransaction();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; list = query.list();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; tx.commit();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } catch (Exception ex) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ex.printStackTrace();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HibernateSessionFactory.rollbackTransaction(tx);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } finally {<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HibernateSessionFactory.closeSession();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return list;<br />
&nbsp;&nbsp; }<br />
<br />
实验结果：<br />
<br />
<br />
补 充一下：当要缓存的对象处于级联关系中时。如果和他存在级联关系的对象都有属性 &lt;cache usage="read-only"/&gt;那么，在第一次get后该对象所处的对象图中的所有对象都会保存到hibernate的二级缓存中，在第二 次get该对象时，直接从二级缓存中找到所有级联的对象；如果其中某个级联对象没有&lt;cache usage="read-only"/&gt;属性，则不会被保存到二级缓存中，以后每次get时仍然会执行sql去数据库中找该级联对象。<br />
&lt;/div&gt;<br />
<br />
来自：<a href="http://jdskyy.javaeye.com/blog/323207" target="_blank">http://jdskyy.javaeye.com/blog/323207</a>
<p>&nbsp;</p>
<p>Hibernate二级缓存也称为进程级的缓存或SessionFactory级的缓存。二级缓存是全局缓存，它可以被所有的session共享。二级缓存的生命周期和SessionFactory的生命周期一致，SessionFactory可以管理二级缓存。<br />
二级缓存的配置使用：<br />
1.在crc下创建echcache.xml文件，其内容如下：</p>
<pre class="xml" style="border-right: #cccccc thin ridge; border-top: #cccccc thin ridge; border-left: #cccccc thin ridge; border-bottom: #cccccc thin ridge; background-color: #f0f0f0" width="500" height="400" name="CodeLight_code">&lt;ehcache&gt;
&lt;diskStore path="java.io.tmpdir"/&gt;
&lt;defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskPersistent="false"
/&gt;
&lt;/ehcache&gt;</pre>
<p>maxElementsInMemory属性用于指定缓存中最多可放多少个对象。<br />
eternal属性指定缓存是否永久有效。<br />
timeToIdleSeconds属性指定缓存多久未被使用便清理掉。<br />
timeToLiveSeconds属性指定缓存的生命长度。<br />
diskPersistent属性指定缓存是否被持久化到硬盘中，保存路径由&lt;diskStore&gt;标签指定。<br />
2.修改hibernate.cfg.xml文件开启二级缓存。</p>
<pre class="xml" style="border-right: #cccccc thin ridge; border-top: #cccccc thin ridge; border-left: #cccccc thin ridge; border-bottom: #cccccc thin ridge; background-color: #f0f0f0" width="500" height="400" name="CodeLight_code">&lt;hibernate-configuration&gt;
&lt;session-factory&gt;
&lt;!-- 开启二级缓存 --&gt;
&lt;property name="hibernate.cache.use_second_level_cache"&gt;true&lt;/property&gt;
&lt;!-- 设置缓存提供者 --&gt;
&lt;property name="hibernate.cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/property&gt;
&lt;mapping resource="cn/ineeke/entity/User.hbm.xml"/&gt;
&lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;</pre>
<p>3.指定哪些实体类使用缓存。经过第二步缓存是启用了，但是并没有被使用。它不会去自动把所有的实体都进行缓存了，而是需要手动指定哪个实体需要缓存，以及其缓存的策略。这里有两种方式，第一种是修改要使用缓存的实体的映射文件。如在User.hbm.xml中使用&lt;cache&gt;标签启用。</p>
<pre class="xml" style="border-right: #cccccc thin ridge; border-top: #cccccc thin ridge; border-left: #cccccc thin ridge; border-bottom: #cccccc thin ridge; background-color: #f0f0f0" width="500" height="400" name="CodeLight_code">&lt;hibernate-mapping&gt;
&lt;class name="cn.ineeke.entity.User" table="t_user"&gt;
&lt;cache usage="read-only"/&gt;
&lt;id name="id"&gt;
&lt;generator class="native"/&gt;
&lt;/id&gt;
&lt;property name="name"/&gt;
&lt;/class&gt;
&lt;/hibernate-mapping&gt;</pre>
<p>第二种方式是在hibernate.cfg.xml中使用&lt;class-cache&gt;标签指定实体类并启用。</p>
<pre class="xml" style="border-right: #cccccc thin ridge; border-top: #cccccc thin ridge; border-left: #cccccc thin ridge; border-bottom: #cccccc thin ridge; background-color: #f0f0f0" width="500" height="400" name="CodeLight_code">&lt;hibernate-configuration&gt;
&lt;session-factory&gt;
&lt;!-- 开启二级缓存 --&gt;
&lt;property name="hibernate.cache.use_second_level_cache"&gt;true&lt;/property&gt;
&lt;!-- 设置缓存提供者 --&gt;
&lt;property name="hibernate.cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/property&gt;
&lt;mapping resource="cn/ineeke/entity/User.hbm.xml"/&gt;
&lt;!-- 指定哪些实体需要使用二级缓存 --&gt;
&lt;class-cache class="cn.ineeke.entity.User" usage="read-only"/&gt;
&lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;</pre>
<p>&lt;calss-cache&gt;标签中的class属性指定要对哪个实体进行缓存，而usage属性与&lt;cache&gt;标签的相同，都指的是缓存策略，此值依实际需要而定，默认采用read-only。</p>
</div>
<script type="text/javascript">
//<![cdata[ Sys.WebForms.PageRequestManager._initialize('AjaxHolder$scriptmanager1', document.getElementById('Form1'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tAjaxHolder$UpdatePanel1'], [], [], 90);
//]]&gt;
</script>
<img src ="http://www.blogjava.net/goldstar/aggbug/305408.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/goldstar/" target="_blank">天外流星</a> 2009-12-10 13:16 <a href="http://www.blogjava.net/goldstar/articles/305408.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>