Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria Restrictions AND / OR combination

How would I achieve this using Hibernate Restrictions?

(((A='X') and (B in('X',Y))) or ((A='Y') and (B='Z'))) 
like image 418
girishsovflow Avatar asked Nov 14 '11 18:11

girishsovflow


People also ask

What is restriction in Hibernate criteria?

The Criteria interface makes it easy to selectively fetch the data on the basis of conditions in the select query. The Restriction class in hibernate provide several methods that can be used as conditions (also known as Criterion). These conditions are added to a criteria object with the add() method.

How do you put restrictions in criteria query?

Restrictions with CriteriaCriteria cr = session. createCriteria(Employee. class); Criterion salary = Restrictions.gt("salary", 2000); Criterion name = Restrictions. ilike("firstNname","zara%"); // To get records matching with OR conditions LogicalExpression orExp = Restrictions.or(salary, name); cr.


2 Answers

think works

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)); 
like image 109
osdamv Avatar answered Sep 18 '22 11:09

osdamv


For the new Criteria since version 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();   
like image 39
FreeOnGoo Avatar answered Sep 22 '22 11:09

FreeOnGoo