2012-08-04 55 views
2

所以,如果我創建一個限制員工我會說休眠條件限制由屬於限制類的實例對象

Criteria crit = sess.createCriteria(Employee.class); 

所以現在我想弄清楚,如果有可能,而不是這樣做的:

List<String> employeeIds; 

Criteria crit = sess.createCriteria(Employee.class); 
crit.add(Restrictions.in("id", employeeIds)); 
crit.createAlias("car", "car"); 
return crit.list(); 

要做到這一點:

List<Employee> employees; 

Criteria crit = sess.createCriteria(Employee.class); 
crit.add(Restrictions.in("", employees));    //Doesn't work, but I think you get what I'm trying to do, query by objects themselves 
crit.createAlias("car", "car"); 
return crit.list(); 

我試圖以限制員工b A查詢y員工對象列表。之後,我會與另一個表進行連接,因此限制我創建條件的類的特定實例列表會很有用。

這將是相同的,因爲這樣本SQL

SELECT * FROM employees 
    JOIN cars 
     ON cars.ownerName like employees.name 
    WHERE employees.id in 
     (<list of employee ids goes here>); 

回答

0

你試試這個?

 Criteria crit = sess.createCriteria(Employee.class, "employee"); 
    crit.add(Restrictions.in("employee", employees)); 
+0

這是我嘗試的第一件事情之一。它最終會沿着「僱員類的未知財產僱員」的方向說。所以它無法神奇地發現我對這些ID感興趣。 到目前爲止,這還不是真正的世界末日,它只是使我的一個便利包裝類沒有我想象的那麼有用。 – iseletsky 2012-08-06 17:45:04

+0

我一直使用「id」屬性,所以我從來沒有碰到你自己確切的問題。我很好奇它是否會起作用。謝謝你讓我知道。 – carbontax 2012-08-06 18:58:01

2

唯一的想法是我做了什麼才能真正獲得您想要檢查的ID列表。限制條件意味着你指定一個屬性,所以「」將不起作用。雖然這是太多的代碼比你貼什麼,我認爲這是解決您發佈的問題的方式:

List<Employee> employees; // This has to be the list o employees 
List<Integer> ids = new ArrayList(); 
Iterator it = employees.iterator(); 
while(it.hasNext()){ 
ids.add(((Employee)it.next()).getId()); 
} 
Criteria crit = sess.createCriteria(Employee.class); 
crit.add(Restrictions.in("id", ids)); 
crit.add(Restriction.eq("car","car")); 

我希望這有助於。