HQL的左连接

最近做一个查询实现把一个表的记录全部显示出来并且显示关联的另外一个表的记录,这当然谁都知道要用到外连接查询,然而过程并不愉快。

在Hibernate的映射文件中配置好关联关系之后,查询的时候可以直接使用比如

select new map(student.studentID as studentID, student.studentAccount as studentAccount,student.studentName as studentName,student.skill.skill as skill) from Student student where student.studentID!=0 and ........

,但是默认使用的内连接,就是说外键必须匹配的记录才能查出来,实现不了要求。
当我决定用左连接查询之后,做了很多尝试,但是因为对HQL不够熟悉,都没有达到要求。比如这样的

select new map(student.studentID as studentID,student.studentAccount as studentAccount,student.studentName as studentName,student.canInterview as canInterview,student.mail as mail,skill.skill as skill,skill.description as description) from Student student left join student.skill skill with student.studentID!=0 and ........
错误,报错:with-clause expressions did not reference from-clause element to which the with-clause
原因因给是是在with语句里面没有用到skill

改成是这样?

select new map(student.studentID as studentID,student.studentAccount as studentAccount,student.studentName as studentName,student.canInterview as canInterview,student.mail as mail,skill.skill as skill,skill.description as description) from Student student left join student.skill skill where student.skill.skillID = skill.skillID and .......
虽然有了skill,但是,报错:with-clause referenced two different from-clause elements

幸好没有崩溃,想起来看一下书。其实怪就怪在没想起来用到join…where,where对字段的限制并没有那么严格,但是因为在Student关联的是Skill实体,又不能直接用where而放弃join,所以,正确的语句:

select new map(student.studentID as studentID,student.studentAccount as studentAccount,student.studentName as studentName,student.canInterview as canInterview,student.mail as mail,skill.skill as skill,skill.description as description) from Student student left join student.skill skill where student.studentID!=0 and ......

注意,上面的student.studentID!=0其实没有起到条件筛选作用,而是为了后面接上and条件不会出错。

你可能感兴趣的:(Java,Web)