日期:2014-05-19  浏览次数:20699 次

求一条HQL语句!内附实体类结构和需求描述...
如题,求一条HQL语句;
以下是一个学员与老师的多对多实体关系案例。描述的关系为:每个学员有很多老师教,每个老师不止教一个学生。
但是由于特殊原因,关系表也映射为实体类了,因为关系表中不仅仅只表述关系问题,还描述了一些其他必要的数据行为,所以三张表都映射成了实体类,根据下面的实体关系描述,应该也是一个完善的多对多关系结构。

现有学员张三,李四,ID分别为1和2;
求HQL语句查询:所有同时教了张三和李四的老师集合。
FROM Teachar ... 后面条件怎么写- -?求大神赐教...


public class Teachar{
    private int id;
    private String name;
    private Set<Relation> relations = new HashSet<Relation>(0);
}

public class Student{
    private int id;
    private String name;
    private Set<Relation> relations = new HashSet<Relation>(0);
}

public class Relation{
    private int id;
    private Teachar teachar;
    private Student student;
    private int state;
    private ...
}




------最佳解决方案--------------------
引用:
引用:
按楼主的需求是在studenId=1中的又要存在于studenId=2中那么
from Teacher t where t.id in(select r.teacher.id from Relation r where r.student.id=1 and r.teacher.id in(select rt.teacher.id from Relatio……

那就继续and r.teacher.id in(查出教王五的老师id) and r.teacher.id in(查出赵六的老师id)....
因为你这个需求是要取他们的交集就是都要存在。
------其他解决方案--------------------
select  b.teachar from Relation b where b.teachar.id in ((select a.teachar.id from Relation a where a.student.id=1)) and b.student.id=2;

------其他解决方案--------------------
from Teacher t where t.id in(select r.teacher.id from Relation r where r.student.id=1 or r.student.id=2);
------其他解决方案--------------------
from Teacher t where t.student.id in (1,2);
------其他解决方案--------------------
1楼没看懂...应该是FROM Teachar
但是2楼和3楼的语句貌似不对啊,
你们这个语句好像查的是“教了张三或者李四的老师”...而不是并且
------其他解决方案--------------------
按楼主的需求是在studenId=1中的又要存在于studenId=2中那么
from Teacher t where t.id in(select r.teacher.id from Relation r where r.student.id=1 and r.teacher.id in(select rt.teacher.id from Relation rt where r2.student.id=2)); 
------其他解决方案--------------------
引用:
按楼主的需求是在studenId=1中的又要存在于studenId=2中那么
from Teacher t where t.id in(select r.teacher.id from Relation r where r.student.id=1 and r.teacher.id in(select rt.teacher.id from Relation rt where r2.student……


.....那我要是查教了张三李四王五赵六等等10个学生的老师呢...HQL语句是什么样的
------其他解决方案--------------------
既然用hql就要面向对象的查询好吗?多对多的关联是不需要建一个Relation中间类的,设置好关联关系hibernate会生成中间表。而且如果同时交了很多人的老师你的sql能写多长啊。hibernate提倡的也是少些sql甚至不写sql的,毕竟还有criteria查询呢。