在网上查了好多资料,发现大家写的都是相互抄的,而且也没有查询过后再jsp页面显示的例子,本人就写了
一个,感觉还是挺方便的,如果哪位高手感觉需要有改进的地方,请不吝赐教!
多表查询
public List<Reply> ListAllReplyTopics(int topic_ID) {
Sessionsession = HibernateUtil.openSession();
Transactiontx = session.beginTransaction();
List<Reply>list=null;
ScrollableResults srs = null;
try{
//Reply和User分别是两个表对应的持久化类
Queryquery=session.createQuery("from Reply re,User user where re.topicID =? and user.userID=re.userID");
query.setInteger(0, topic_ID);
list=(List<Reply>)query.list();
System.out.println(list.size());
//tx.commit();
}catch(Exception ex) {
ex.printStackTrace();
}finally{
HibernateUtil.close(session);// 关闭session
}
return list;
}
因为多表查询返回list默认是返回一个对象的结果,所以在jsp页面显示时可以利用一下:
Jsp:显示
其中replyTopics[1]表示第一个对象,replyTopics[0]表示第零个对象。对象的顺序跟你的hql语句的顺序一一对应,千万别弄混了
<tr>
<td><s:a href="getAuthorInfo.action?authorID=%{#replyTopics[1].userID}&&userName=%{#replyTopics[1].userName}&&pageNow=1&&userID=%{#request.userID}&&flag=0"><s:propertyvalue="#replyTopics[1].userName" /></s:a>
</td>
<td><s:property value="#request.topic.title"/>
</td>
<td><s:property value="#replyTopics[0].content"escapeHtml="false" />
</td>
<td><s:property value="#replyTopics[0].publishDate"/>
</td>
</tr>