iseletsky
iseletsky

Reputation: 653

Hibernate Criteria restriction by objects that are instances of the restriction class

So if I'm creating a restriction for employees I'd say

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

So now I'm trying to figure out if it's possible to instead of doing this:

List<String> employeeIds;

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

To do this:

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();

I'm trying to restrict a query for Employees by a list of employee objects. Later I do a join with another table, so it's useful to restrict by a list of specific instances of the class that I'm creating a criteria for.

This would be the same as this sample SQL

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

Upvotes: 2

Views: 1826

Answers (2)

Moises
Moises

Reputation: 45

The only idea I get to do what you what is to actually obtain a list of the ids you want to check. The Restrictions.in implies that you specify a property so "" will not work. Even though this is much more code than what you posted, I think this is the way to solve the question you posted:

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"));

I hope this helps.

Upvotes: 2

carbontax
carbontax

Reputation: 2184

Did you try this?

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

Upvotes: 0

Related Questions