Source Allies Logo

Sharing Our Passion for Technology

& Continuous Learning

<   Back to Blog

Hibernate Criteria trick

So here's the situation.

Let's say I have this query here:

SELECT * FROM employees
WHERE employee_id NOT IN ( 1234 , 3456 , 5678 );

How do we do that with the Hibernate Criteria object with a Restriction? You would think that the Restrictions API would have a "not in" method, since it does have a not equals method(ne), but alas, there is nothing...

Well, here's the solution:

//Create the criteria
Criteria crit = factory.getCurrentSession().createCriteria(Employee.class);

//add my restriction where idList is a list of emp ids that need to be excluded
crit.add(Restrictions.not(Restrictions.in("employeeId", idList)));

//get some results
List employees = crit.list();

There you go! Now you know this neat little trick and you can use it in your own app... Be forewarned though, it can be slow...