2014-05-08 88 views
0

这里是我的数据库结构:Hibernate查询 - 似乎无法比较所有数据集?

Foo: //foo class 
     Set<Students> students; 
     Set<Teachers> teachers; 
    //students 
    Students: 
     Int id; 
     String name; 
    //teachers 
    Teachers: 
     Int id; 
     String name; 


    Criteria criteria = sess.createCriteria(Foo.class ,"foo"). 
          createAlias("students", "student"). 
          createAlias("teachers","teacher"); 

    //create and statement for the student id 

    Conjunction andStudent = Restriction.conjunction(); 
    for (Student student : currentFoo.students) { 
     andStudent.add(Restrictions.eq("student.id", student.id)); 
    } 

基本上我想创建一个Hibernate查询,其中给予富的清单,我想找到FOOS这一切都是我比较了富学生和老师一致。因此,如果currentFoo的学生ID为1,3和教师ID为2,4,我希望查询返回包含BOTH Student ID 1,3和Teacher ID 2,4的Foos以及其他可能包含的任何其他内容。

我运行查询后(照顾的独特效果和去除currentFoo结果)我得到0结果...

我的确从2行的ID删除数据从currentFoo行的学生之一1,2到1的一行,我得到了结果 - 所以在我看来,问题的一个部分是在查询过程中,第二行学生不被比较或读入?有人可以帮忙吗?谢谢!

回答

0

在这种情况下,您不想使用eqCriterioninCriterion是你需要的。一个是建立学生ID的集合替换你的循环,然后你可以使用一个(非循环)限制:

andStudent.add(Restrictions.in("student.id", collectionOfStudentIds)); 

你甚至可以简单地做

andStudent.add(Restrictions.in("student", collectionOfStudents)); 

但我有一段时间没有用过,所以我忘了它是否可行。

+0

谢谢你的回复。我以前使用过Restrictions.in,但是它的功能是返回Foo,如果有任何id匹配的话。例如,如果Foo的ID为1,3,我将其与学号为1,4,5的Foo进行比较,即使它不应该是结果,我也会得到该结果...... – user3618456

+0

这就是为什么您使用连词。你需要逻辑如“currentFoo中的studentA和currentFoo中的studentB以及currentFoo中的teacherX和currentFoo中的teacherY” –

+0

你还可以添加额外的标准,如“学生的数量= 2和教师的数量= 2”以获得所需的最后一位逻辑 –