How to achieve "not in" by using Restrictions and criteria in Hibernate?

Shashi picture Shashi · Aug 3, 2009 · Viewed 64.9k times · Source

I have list of category. I need a list of category by excluding 2,3 row. Can we achieve through hibernate by using Criteria and Restriction?

Answer

ChssPly76 picture ChssPly76 · Aug 3, 2009

Your question is somewhat unclear. Assuming "Category" is a root entity and "2,3" are ids (or values of some property of the category") you can exclude them using the following:

Criteria criteria = ...; // obtain criteria from somewhere, like session.createCriteria() 
criteria.add(
  Restrictions.not(
     // replace "id" below with property name, depending on what you're filtering against
    Restrictions.in("id", new long[] {2, 3})
  )
);

Same can be done with DetachedCriteria.