Hibernate Criteria Restrictions AND / OR 组合
Posted
技术标签:
【中文标题】Hibernate Criteria Restrictions AND / OR 组合【英文标题】:Hibernate Criteria Restrictions AND / OR combination 【发布时间】:2011-12-28 22:06:52 【问题描述】:如何使用 Hibernate Restrictions 来实现这一点?
(((A='X') and (B in('X',Y))) or ((A='Y') and (B='Z')))
【问题讨论】:
【参考方案1】:认为有效
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));
【讨论】:
【参考方案2】:对于自 Hibernate 5.2 版本以来的新标准:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
【讨论】:
以上是关于Hibernate Criteria Restrictions AND / OR 组合的主要内容,如果未能解决你的问题,请参考以下文章