我有类别列表。我需要一个排除 2,3 行的类别列表。我们可以通过使用 Criteria 和 Restriction 通过 hibernate 来实现吗?
你的问题有点不清楚。假设“类别”是根实体,“2,3”是 id(或类别的某些属性的值),您可以使用以下命令排除它们:
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 版本以来的新标准:
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();
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();