52

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

4

3 回答 3

108

你的问题有点不清楚。假设“Category”是一个根实体,“2,3”是 ids(或该类别的某些属性的值),您可以使用以下命令排除它们:

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.

于 2009-08-03T17:07:34.933 回答
3

对于自 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();
于 2019-06-15T19:07:17.247 回答
1
 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();
于 2010-05-19T05:46:57.427 回答