2014-05-08 25 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」以獲得所需的最後一位邏輯 –