在hibernate映射文件中通过sql-query实现多表级联查询:
<sql-query name="findMes">
SELECT {mt.*} from (select u.USERNAME
as username,t.TALK_ID as talkId,t.TOPIC_ID as topicId,
u1.USERNAME as rusername, root.TOPIC_ID as rtopicId,root.TALK_TYPE as rtalkType from
tb_talk t left join tb_user u on u.USER_ID=t.USER_ID left join tb_talk root
on root.TALK_ID=t.ROOT_ID left join tb_user u1 on u1.USER_ID=root.USER_ID
where t.TOPIC_ID=:p1order by t.TALK_ID )mt
<return alias="mt" class="com.tvfan.vo.TalkVO" />
</sql-query>其中包含自连接
dao层实现如下:
HibernateTemplate ht = new HibernateTemplate(this.getSessionFactory());
return (List<TalkVO>) ht.execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Query query = session.getNamedQuery("findMes");
query.setLong("p1", p1);
List<TalkVO> lst=query.list();
return lst;
}
});