如何通过使用Hibernate中的限制和条件来实现”不参与”?

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

我有类别列表。我需要一个排除2,3行的类别列表。我们可以通过使用Criteria and Restriction来通过hibernate来实现吗?


您的问题尚不清楚。假设" Category "是根实体," 2,3 "是ID(或类别"的某些属性的值),则可以使用以下命令排除它们:

1
2
3
4
5
6
7
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})
  )
);

DetachedCriteria可以完成相同的操作。


对于Hibernate 5.2版本以后的新标准:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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();

1
2
3
4
5
6
 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();