2012-08-04 57 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")); 

我希望这有助于。