二张表分别为用户表(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>
.....
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>
......
注意:如果多表查询,在写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();
}
在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>
分享到:
相关推荐
hibernate 多表查询 hibernate 多表不同于一般的sql嵌套查询,嵌套查询是不支持的,所以必须要配置好才能实现多表!只要配置好了,还是特别好用的
Hibernate连表查询 Hibernate连表查询
hibernate多表联合查询实例,很经典的查询语句和总结.
该源代码配了了解释,针对hibernate中多表查询的多种形式进行了总结,很有价值,有Object[]形式的查询,也有对象方式的查询 也有集合list形式的查询,
Hibernate 多表连接分页查询示范项目 Hibernate Criteria 多表连接 分页
Hibernate多表查询.txt
hibernate多表查询[定义].pdf
Hibernate 多表映射关系配置 如,一对一 多对一 多对多等
NULL 博文链接:https://08284008.iteye.com/blog/1456476
Hibernate多对多关联添加及查询示例
NULL 博文链接:https://gaoquanyang.iteye.com/blog/1213765
使用Struts2+Hibernate实现对部门表、员工表两张表的增删改查。
Hibernate中使用Criteria Query各种QBC查询
hibernate实现动态表查询的多种解决方案.自行整理的动太实现方案,总有一个适合你.
Hibernate_query查询数据表中的一个字段.
Hibernate_QBC查询
Hibernate中的关联查询实际上生成的是数据库表连接查询的SQL语句
利用MYSQL数据库提供的样例数据库world建立的查询小例子。已经建立好了数据库对应的...本项目主要是为了练习使用Hibernate查询数据库。如果有什么问题可以发站内信或者邮件asddf14@hotmail.com。我会尽量解答一下~~~
struts2+hibernate+spring多表操作
博客对应代码