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条件不会出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值