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

HibernateCriteriaRestriction

Hibernate Problem Overview


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?

Hibernate Solutions


Solution 1 - Hibernate

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.

Solution 2 - Hibernate

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<Comment> criteriaQuery = criteriaBuilder.createQuery(Comment.class);

List<Long> ids = new ArrayList<>();
ids.add(2L);
ids.add(3L);

Root<Comment> root = getRoot(criteriaQuery);
Path<Object> fieldId = root.get("id");
Predicate in = fieldId.in(ids);
Predicate predicate = criteriaBuilder.not(in);

criteriaQuery
        .select(root)
        .where(predicate);

List<Comment> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();

Solution 3 - Hibernate

 Session session=(Session) getEntityManager().getDelegate();
        Criteria criteria=session.createCriteria(RoomMaster.class);
//restriction used or inner restriction ...
        criteria.add(Restrictions.not(Restrictions.in("roomNumber",new String[] { "GA8", "GA7"})));
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        List<RoomMaster> roomMasters=criteria.list();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShashiView Question on Stackoverflow
Solution 1 - HibernateChssPly76View Answer on Stackoverflow
Solution 2 - HibernateFreeOnGooView Answer on Stackoverflow
Solution 3 - HibernatesouravView Answer on Stackoverflow