Hibernate多对多查询

一个老师教许多学生,一个学生被许多老师教,一个学生有好多书,同一种书被许多同学拥有.
要查询教拥有书"a"的学生的老师!

HQL如何写呀?如何取值? 

class  Teacher{ 
String id; 
String name; 
Set students; 

class  Student{ 
String id; 
String name; 
Set teachers; 
Set books; 

class  Book{ 
String id; 
String name; 
Set students; 

 

< class  name ="net.fengrun.lzk.stu.Book"  table ="books" >  
< id  name ="id"  type ="integer"  column ="id" >  
< generator  class ="native" />  
</ id >  
< property  name ="name" />  
< set  name ="students"  table ="student_book"  inverse ="true"  cascade ="none"  lazy ="true" >  
< key  column ="bookid" />  
< many-to-many  column ="studentid"  class ="net.fengrun.lzk.stu.Student" />  
</ set >  
</ class >  

< class  name ="net.fengrun.lzk.stu.Student"  table ="students" >  
< id  name ="id"  type ="integer"  column ="id" >  
< generator  class ="native" />  
</ id >  
< property  name ="name" />  
< set  name ="books"  table ="student_book"  inverse ="false"  cascade ="none"  lazy ="true" >  
< key  column ="studentid" />  
< many-to-many  column ="bookid"  class ="net.fengrun.lzk.stu.Book" />  
</ set >  
< set  name ="teachers"  table ="teacher_student"  inverse ="false"  cascade ="none"  lazy ="true" >  
< key  column ="studentid" />  
< many-to-many  column ="teacherid"  class ="net.fengrun.lzk.stu.Teacher" />  
</ set >  
</ class >  

< class  name ="net.fengrun.lzk.stu.Teacher"  table ="teachers" >  
< id  name ="id"  type ="integer"  column ="id" >  
< generator  class ="native" />  
</ id >  
< property  name ="name" />  
< set  name ="students"  table ="teacher_student"  inverse ="true"  cascade ="delete-orphan"  lazy ="true"   >  
< key  column ="teacherid" />  
< many-to-many  column ="studentid"  class ="net.fengrun.lzk.stu.Student" />  
</ set >  
</ class >  

Hql语句:

SELECT t FROM Teacher t join t.students s join s.books b where b.name = 'a' 

解释:t.students s中s并不是集合的意思,而是t的students对象的表别名,join t.students s这个hql,hibernate会翻译成两个表的内连接关系

错误写法:

SELECT t FROM teacher t where t.students.books.name = 'a' 

其实道理是很显然的,t.students是一个Set,那么这个Set怎么可能有books这样的属性呢?同理books.name也不对,所以使用表间连接并给出别名t.students s,此时的对象s才有books属性,所以可以写s.books b,最后使用b.name限制查询b.name = 'a'. 

另外一种写法:

SELECT t FROM Teacher t,Student s,Book b where s.id in elements(t.students) and b.id in elements(s.books)
这种方法没有出错!不过这种方式要用子查询! 但是MySql并不支持子查询,为了通用性,选择第一种做法。

未完,待续...


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值