﻿<?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/hilor/category/25383.html</link><description>我的学习档案馆</description><language>zh-cn</language><lastBuildDate>Wed, 05 Dec 2007 09:01:44 GMT</lastBuildDate><pubDate>Wed, 05 Dec 2007 09:01:44 GMT</pubDate><ttl>60</ttl><item><title>Hibernate类的initialize()静态方法使用</title><link>http://www.blogjava.net/hilor/archive/2007/12/04/165144.html</link><dc:creator>hilor</dc:creator><author>hilor</author><pubDate>Tue, 04 Dec 2007 05:26:00 GMT</pubDate><guid>http://www.blogjava.net/hilor/archive/2007/12/04/165144.html</guid><wfw:comment>http://www.blogjava.net/hilor/comments/165144.html</wfw:comment><comments>http://www.blogjava.net/hilor/archive/2007/12/04/165144.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/hilor/comments/commentRss/165144.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/hilor/services/trackbacks/165144.html</trackback:ping><description><![CDATA[<font color="#000000">Hibernate类的initialize()静态方法用于在Session范围内显式初始化代理类实例，isInitialized()方法用于判断代理类实例是否已经被初始化。例如： </font>
<p><font color="#000000"><span style="color: #003366">tx = session.beginTransaction(); <br />
Customer customer=(Customer)session.load(Customer.class,new Long(1)); <br />
if(!Hibernate.isInitialized(customer)) <br />
Hibernate.initialize(customer); <br />
tx.commit(); <br />
session.close(); <br />
customer.getName();</span> </font></p>
<p><span style="color: #003366"><font color="#000000">以上代码在Session范围内通过Hibernate类的initialize()方法显式初始化了Customer代理类实例，因此当Session关闭后，可以正常访问Customer游离对象。</font></span></p>
<img src ="http://www.blogjava.net/hilor/aggbug/165144.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/hilor/" target="_blank">hilor</a> 2007-12-04 13:26 <a href="http://www.blogjava.net/hilor/archive/2007/12/04/165144.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Hibernate3的DetachedCriteria使用</title><link>http://www.blogjava.net/hilor/archive/2007/09/14/145172.html</link><dc:creator>hilor</dc:creator><author>hilor</author><pubDate>Fri, 14 Sep 2007 08:27:00 GMT</pubDate><guid>http://www.blogjava.net/hilor/archive/2007/09/14/145172.html</guid><wfw:comment>http://www.blogjava.net/hilor/comments/145172.html</wfw:comment><comments>http://www.blogjava.net/hilor/archive/2007/09/14/145172.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/hilor/comments/commentRss/145172.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/hilor/services/trackbacks/145172.html</trackback:ping><description><![CDATA[Criteria對SQL進行封裝，讓開發人員可以用物件的方式來對資料庫進行操作，例如下面的查詢User表格中的所有資料：<br />
<div style="margin-left: 40px"><span style="font-weight: bold; font-family: Courier New,Courier,monospace">Criteria criteria = session.createCriteria(User.class);</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">// 查詢user所有欄位</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">List users = criteria.list();</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">Iterator iterator =&nbsp; users.iterator();</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">System.out.println("id \t name/age");</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">while(iterator.hasNext()) {</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">&nbsp;&nbsp;&nbsp; User user = (User) iterator.next(); </span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">&nbsp;&nbsp;&nbsp; System.out.println(user.getId() +</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; " \t " + user.getName() +</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "/" + user.getAge());&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">}</span><br />
</div>
<br />
Hibernate實際上使用以下的SQL來查詢資料庫：<br />
<div style="margin-left: 40px"><span style="font-weight: bold; font-family: Courier New,Courier,monospace">select this_.id as id0_, this_.name as name0_0_, this_.age as age0_0_ from user this_</span><br />
</div>
<br />
Criteria實際上只是個容器，如果想要設定查詢條件，則要使用add()方法加入Restrictions的條件限制，例如查詢age大於20且小於40的資料：<br />
<div style="margin-left: 40px"><span style="font-weight: bold; font-family: Courier New,Courier,monospace">Criteria criteria = session.createCriteria(User.class);</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">criteria.add(Restrictions.gt("age", new Integer(20)));</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">criteria.add(Restrictions.lt("age", new Integer(40)));</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">List users = criteria.list();</span><br />
</div>
<br />
您也可以使用邏輯組合來進行查詢，例如結合age等於（eq）20或（or）age為空（isNull）的條件： <br />
<div style="margin-left: 40px"><span style="font-weight: bold; font-family: Courier New,Courier,monospace">Criteria criteria = session.createCriteria(User.class);</span><br style="font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">criteria.add(Restrictions.or( </span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Restrictions.eq("age", new Integer(20)), </span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; Restrictions.isNull("age") </span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)); </span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">List users = criteria.list();</span><br />
</div>
<br />
也可以使用sqlRestriction()方法來提供SQL語法作限定查詢，例如查詢name以cater開頭的資料：<br />
<div style="margin-left: 40px"><span style="font-weight: bold; font-family: Courier New,Courier,monospace">Criteria criteria = session.createCriteria(User.class);</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">criteria.add(Restrictions.sqlRestriction("{alias}.name LIKE (?)", "cater%", Hibernate.STRING));</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">List users = criteria.list();</span><br />
</div>
<br />
其中alias將被替換為與User類別相關的名稱，而?將被替換為cater%，也就是第二個參數所提供的值，在SQL撰寫時，不必再寫WHERE，如果有多個查詢條件，例如BETWEEN子句的查詢，則可以如下：<br />
<div style="margin-left: 40px"><span style="font-weight: bold; font-family: Courier New,Courier,monospace">Criteria criteria = session.createCriteria(User.class);</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">Integer[] ages = {new Integer(20), new Integer(40)};</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">Type[] types = {Hibernate.INTEGER, Hibernate.INTEGER};</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">criteria.add(Restrictions.sqlRestriction("{alias}.age BETWEEN (?) AND (?)", ages, types));</span><br style="font-weight: bold; font-family: Courier New,Courier,monospace" />
<span style="font-weight: bold; font-family: Courier New,Courier,monospace">List users = criteria.list();</span><br />
</div>
<br />
Restrictions的幾個常用限定查詢方法如下表所示：<br />
<table style="width: 100%; text-align: left" cellspacing="2" cellpadding="2" border="1">
    <tbody>
        <tr>
            <td style="background-color: rgb(204,204,204)"><small>方法</small></td>
            <td style="background-color: rgb(204,204,204)"><small>說明</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.eq</small></td>
            <td><small>等於</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.allEq</small></td>
            <td><small>使用Map，使用key/value進行多個等於的比對</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.gt</small></td>
            <td><small>大於 &gt;</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.ge</small></td>
            <td><small>大於等於 &gt;=</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.lt</small></td>
            <td><small>小於 &lt;</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.le</small></td>
            <td><small>小於等於 &lt;=</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.between</small></td>
            <td><small>對應SQL的BETWEEN子句</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.like</small></td>
            <td><small>對應SQL的LIKE子句</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.in</small></td>
            <td><small>對應SQL的in子句</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.and</small></td>
            <td><small>and關係</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.or</small></td>
            <td><small>or關係</small></td>
        </tr>
        <tr>
            <td><small>Restrictions.sqlRestriction</small></td>
            <td><small>SQL限定查詢</small></td>
        </tr>
    </tbody>
</table>
<p><br />
&nbsp;</p>
<p>&nbsp;</p>
<p>==============</p>
<p>&nbsp;</p>
<h2><a id="_ctl0__ctl2_TitleUrl" href="http://java.mblogger.cn/fyun/posts/17316.aspx">Hibernate Criteria 关联查询</a> </h2>
<p>前面讲了Criteria看起来比HQL顺眼多了，接着继续。<br />
<br />
如果每个美女都有自己的客户资源（不要想歪了！），那么需要查询拥有客户Gates的美女怎么办？<br />
<br />
使用Criteria可以有两种方法：<br />
<br />
1：<br />
DetachedCriteria beautyCriteria = DetachedCriteria.forClass(Beauty.class).createCriteria("customers");<br />
beautyCriteria.add(Restrictions.eq("name", "Gates")):<br />
<br />
2：<br />
DetachedCriteria beautyCriteria = DetachedCriteria.forClass(Beauty.class).createAlias("customers", "c");<br />
beautyCriteria.add(Restrictions.eq("c.name", "Gates")):<br />
<br />
接着有了新的要求，年纪太大的美女不要，还是查找拥有客户Gates的，条件如下：<br />
DetachedCriteria beautyCriteria = DetachedCriteria.forClass(Beauty.class, "b").;<br />
DetachedCriteria customerCriteria = beautyCriteria.createAlias("customers", c");<br />
beautyCriteria.add(Restrictions.le("b.age", new Long(20))):<br />
customerCriteria.add(Restrictions.eq("c.name", "Gates")):<br />
<br />
关于Criteria更详细的资料，Hibernate的源代码和测试是最好的文档。<br />
<br />
Criteria的缺点？DBA很生气，后果很严重。</p>
<img src ="http://www.blogjava.net/hilor/aggbug/145172.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/hilor/" target="_blank">hilor</a> 2007-09-14 16:27 <a href="http://www.blogjava.net/hilor/archive/2007/09/14/145172.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>