`
anson_xu
  • 浏览: 502413 次
  • 性别: Icon_minigender_1
  • 来自: 惠州
社区版块
存档分类

hibernate多表查询

阅读更多
hibernate多表查询
关键字: hibernate
我的demo小程序随着我学习的过程、体积也越来越庞大起来了、开始只是用来测试hibernate、渐渐的Spring,struts,dwr(我在用来做验证的过程因为异步,效果反而不好,所以后来拿掉了)的身影也出现了,到如今他已经有注册、登陆、发贴、查看主题、查看跟贴,回贴的能耐了,呵呵,为他而高兴。在前面学习的过程中先避开一些难点,比如多表查询、AOP切面编程等等,不过为了满足需求,今天开始将多表应用上去了,确实遇到了不少麻烦,花了不少的时间,当然在遇到问题,解决问题的过程中让我回顾了很多要点、盲点,也值了。
现在将关键点记录下来,以免日后再有相同问题出现,以便查阅。
二张表分别为用户表(users)和贴子表(notes),其中users中的userid是notes表的外键,users跟notes是一对多,多对一关系,由myEclpise自动生成映射文件
Users.hbm.xml

Java代码
......  
 
<set name="noteses" inverse="true">  
     <key>  
         <column name="userid" not-null="true" />  
     </key>  
     <one-to-many class="com.note.model.Notes" />  
</set>  
 
..... 

       ......

        <set name="noteses" inverse="true">
            <key>
                <column name="userid" not-null="true" />
            </key>
            <one-to-many class="com.note.model.Notes" />
        </set>

      ......

Notes.hbm.xml

Java代码
......  
 
  <many-to-one name="users" class="com.note.model.Users" fetch="select">  
      <column name="userid" not-null="true" />  
  </many-to-one>  
 
...... 

      ......

        <many-to-one name="users" class="com.note.model.Users" fetch="select">
            <column name="userid" not-null="true" />
        </many-to-one>

      ......

注意:如果多表查询,在写HQL语句时取notes的userid字段不能写notes.userid(这个问题下午我查了好久,才找到原因的)

HQL语句:From Notes notes,Users users WHERE notes.users=users.userid AND notes.issubject=1

又一注意点:该查询结果为存放对象数组的list集,可以用以下代码测试

Java代码
                   page=ins.listSubjects(page);//page是我的分页类,并存放了查询后的返回结果  
List list=page.getResult();  
System.out.println(page.getPageToolBar());  
for(int i=0;i<list.size();i++){  
    Object[] obj=(Object[])list.get(i);  
    for(int j=0;j<obj.length;j++){  
        if(obj[j] instanceof Notes){  
            Notes note=(Notes)obj[j];  
            System.out.print(note.getTitle());  
              
        }else if(obj[j] instanceof Users){  
            Users user=(Users)obj[j];  
            System.out.print(user.getUsername());  
        }  
    }  
    System.out.println();  


                     page=ins.listSubjects(page);//page是我的分页类,并存放了查询后的返回结果
List list=page.getResult();
System.out.println(page.getPageToolBar());
for(int i=0;i<list.size();i++){
Object[] obj=(Object[])list.get(i);
for(int j=0;j<obj.length;j++){
if(obj[j] instanceof Notes){
Notes note=(Notes)obj[j];
System.out.print(note.getTitle());

}else if(obj[j] instanceof Users){
Users user=(Users)obj[j];
System.out.print(user.getUsername());
}
}
System.out.println();
}

在jsp页面显示结果的时候我觉得用EL表达式会简单的多,如:
Java代码
<logic:present name="subjects">  
        <table width="100%" border="1" rules="rows" frame="below" cellpadding="5" cellspacing="0" bordercolorlight="#6C7BA6" bordercolordark="#ffffff" bgcolor="#DEEFFF" class="DoubleColorTable">  
            <logic:present name="subjects" property="result">  
            <logic:iterate id="objs" name="subjects" indexId="number" property="result">  
                <tr>  
                    <td>  
                    <html:link page="/listFollow.do?method=listFollow&subjectId=${objs[0].noteid}"  styleId="link001">  
                        主题:${objs[0].title}  
                    </html:link>  
                    </td>  
                    <td>  
                    作者:${objs[1].username}  
                    </td>  
                    <td>  
                    发贴时间:${objs[0].addtime}  
                    </td>  
                </tr>  
            </logic:iterate>  
            </logic:present>  
        </table>  
        <bean:write name="subjects" property="pageToolBar" filter="false" />  
    </logic:present> 

<logic:present name="subjects">
<table width="100%" border="1" rules="rows" frame="below" cellpadding="5" cellspacing="0" bordercolorlight="#6C7BA6" bordercolordark="#ffffff" bgcolor="#DEEFFF" class="DoubleColorTable">
<logic:present name="subjects" property="result">
<logic:iterate id="objs" name="subjects" indexId="number" property="result">
<tr>
<td>
<html:link page="/listFollow.do?method=listFollow&subjectId=${objs[0].noteid}"  styleId="link001">
主题:${objs[0].title}
</html:link>
</td>
<td>
作者:${objs[1].username}
</td>
<td>
发贴时间:${objs[0].addtime}
</td>
</tr>
</logic:iterate>
</logic:present>
</table>
<bean:write name="subjects" property="pageToolBar" filter="false" />
</logic:present>19:01 浏览 (12857) 评论 (17) 分类: java技术 进入论坛 收藏 相关推荐 评论
magic.chen 2007-09-11
请问:延迟加载能支持多表查询吗?支持的话,怎么去掉重复数据(set吗?),那要是排序呢?
sun113 2006-11-12
有收获,写得不赖!
wiley 2006-11-11
sun113 写道
又一注意点:该查询结果为存放对象数组的list集,可以用以下代码测试

请问list集中存放的是什么,使相关的user对象和note对象,对不对?

是的,list中存放你所查询对po的集合,多个对象以数组构建list
sun113 2006-11-11
又一注意点:该查询结果为存放对象数组的list集,可以用以下代码测试

请问list集中存放的是什么,使相关的user对象和note对象,对不对?
andyao 2006-11-09
wiley 写道
[quote=ppm10103 ]hibernate多表查询时可以采用延迟加载来提高效率,这应该是一种方法吧,不过我还有一个问题,在1:N的情况下,如果是1:10000那延迟加载时是不是会把10000条都加载进来,能不能控时加载数量呀?
--------
延迟加载加载的是代理类,如果不显示访问是不会加载内容的,
如果允许外连接也要控制一下连接深度

今天用DWR+Spring做整合时,发现真的跟你说的一样,确实是只要显式访问时才加载,不过通过DWR去迟加载时说session已被关闭.这个问题怎么解决呢


Hibernate文档里面有说明,应该多看看文档

19.1.1. Working with lazy associations
By default, Hibernate3 uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for almost all associations in almost all applications.

Note: if you set hibernate.default_batch_fetch_size, Hibernate will use the batch fetch optimization for lazy fetching (this optimization may also be enabled at a more granular level).

However, lazy fetching poses one problem that you must be aware of. Access to a lazy association outside of the context of an open Hibernate session will result in an exception. For example:
Java代码
s = sessions.openSession();  
Transaction tx = s.beginTransaction();  
              
User u = (User) s.createQuery("from User u where u.name=:userName")  
    .setString("userName", userName).uniqueResult();  
Map permissions = u.getPermissions();  
 
tx.commit();  
s.close();  
 
Integer accessLevel = (Integer) permissions.get("accounts");  // Error! 

s = sessions.openSession();
Transaction tx = s.beginTransaction();
           
User u = (User) s.createQuery("from User u where u.name=:userName")
    .setString("userName", userName).uniqueResult();
Map permissions = u.getPermissions();

tx.commit();
s.close();

Integer accessLevel = (Integer) permissions.get("accounts");  // Error!

Since the permissions collection was not initialized when the Session was closed, the collection will not be able to load its state. Hibernate does not support lazy initialization for detached objects. The fix is to move the code that reads from the collection to just before the transaction is committed.

Alternatively, we could use a non-lazy collection or association, by specifying lazy="false" for the association mapping. However, it is intended that lazy initialization be used for almost all collections and associations. If you define too many non-lazy associations in your object model, Hibernate will end up needing to fetch the entire database into memory in every transaction!

On the other hand, we often want to choose join fetching (which is non-lazy by nature) instead of select fetching in a particular transaction. We'll now see how to customize the fetching strategy. In Hibernate3, the mechanisms for choosing a fetch strategy are identical for single-valued associations and collections.
wiley 2006-11-09
[quote=ppm10103 ]hibernate多表查询时可以采用延迟加载来提高效率,这应该是一种方法吧,不过我还有一个问题,在1:N的情况下,如果是1:10000那延迟加载时是不是会把10000条都加载进来,能不能控时加载数量呀?
--------
延迟加载加载的是代理类,如果不显示访问是不会加载内容的,
如果允许外连接也要控制一下连接深度

今天用DWR+Spring做整合时,发现真的跟你说的一样,确实是只要显式访问时才加载,不过通过DWR去迟加载时说session已被关闭.这个问题怎么解决呢
ppm10103 2006-11-06
hibernate多表查询时可以采用延迟加载来提高效率,这应该是一种方法吧,不过我还有一个问题,在1:N的情况下,如果是1:10000那延迟加载时是不是会把10000条都加载进来,能不能控时加载数量呀?
--------
延迟加载加载的是代理类,如果不显示访问是不会加载内容的,
如果允许外连接也要控制一下连接深度
wiley 2006-11-05
hibernate多表查询时可以采用延迟加载来提高效率,这应该是一种方法吧,不过我还有一个问题,在1:N的情况下,如果是1:10000那延迟加载时是不是会把10000条都加载进来,能不能控时加载数量呀?
wiley 2006-11-02
santafeng 写道
wiley 写道
to:santafeng

引用
这样做很好啊,不如用排序组合算法算了。拿出数据集合还需新组装成页面需求集合,几乎说是严重浪费人力物力表现。真不知道你是如何想得。


我也是初学hibernate,并不是很深入,你能详述你在多表查询时的做法吗?谢谢


这种设计使用hibernate无疑是鸡肋表现,无法解决。


那什么样的设计才使用hibernate呢?
santafeng 2006-11-02
wiley 写道
to:santafeng

引用
这样做很好啊,不如用排序组合算法算了。拿出数据集合还需新组装成页面需求集合,几乎说是严重浪费人力物力表现。真不知道你是如何想得。


我也是初学hibernate,并不是很深入,你能详述你在多表查询时的做法吗?谢谢


这种设计使用hibernate无疑是鸡肋表现,无法解决。
wiley 2006-11-02
to:santafeng

引用
这样做很好啊,不如用排序组合算法算了。拿出数据集合还需新组装成页面需求集合,几乎说是严重浪费人力物力表现。真不知道你是如何想得。


我也是初学hibernate,并不是很深入,你能详述你在多表查询时的做法吗?谢谢
wiley 2006-11-02
引用
注意:如果多表查询,在写HQL语句时取notes的userid字段不能写notes.userid(这个问题下午我查了好久,才找到原因的)

HQL语句:From Notes notes,Users users WHERE notes.users=users.userid AND notes.issubject=1

问下 为何不能写成notes.userid 而要notes.users?


Users(POJO)中没有userid成员
jd2bs 2006-11-02
注意:如果多表查询,在写HQL语句时取notes的userid字段不能写notes.userid(这个问题下午我查了好久,才找到原因的)

HQL语句:From Notes notes,Users users WHERE notes.users=users.userid AND notes.issubject=1

问下 为何不能写成notes.userid 而要notes.users?
santafeng 2006-11-02
这样做很好啊,不如用排序组合算法算了。拿出数据集合还需新组装成页面需求集合,几乎说是严重浪费人力物力表现。真不知道你是如何想得。
cncomkyle 2006-11-01
我把你的查选考虑成外连接了,如果是外连接,会有出现null的情况
wiley 2006-11-01
obj[j]应该不会出现null,只有list才有可能出现null所以在循环外加if判断就可以了
cncomkyle 2006-11-01
if(obj[j] instanceof Notes){
Notes note=(Notes)obj[j];
System.out.print(note.getTitle());

}else if(obj[j] instanceof Users){
Users user=(Users)obj[j];
System.out.print(user.getUsername());
}
当obj[j]为null时的情况,怎么样处理呢
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics