How to use the AND OR operator in sleep mode

I have a requirement to use the AND / OR operator for a sleeping isolated criteria request. I want to emulate the SQL equivalent:

Select * from myTable where city in ( X, Y ) OR city in (A,B);  

// Note that I need to use a few 'In' here

How to create a citeria query to use the OR operator.

Sort of

DetachedCriteria criteria = DetachedCriteria.forClass(
    myClass.class)
   .add(Property.forName("city").in(X,Y));
criteria.**Or**(add(Property.forName("city").in(X,Y));

Unfortunately, there is no OR method in the criteria, just add it.

Thanks in advance

+3
source share
2 answers

Use Restrictions.conjunction()and Restrictions.disjunction()to create a hierarchy of conditions.

Look here - section 15.2 and here


EDIT:

I believe your code is Property.forName("city").in(X,Y))correct (I do not remember this clause)

DetachedCriteria criteria = DetachedCriteria.forClass(
    myClass.class)
   .add(Restrictions.disjunction()
       .add( Property.forName("city").in(X,Y) )
       .add(Property.forName("city").in(X,Y)  )
   );
+9
source

:

1.0:

Criteria myQueryCrit = session.createCriteria(XYZ.class, "xyz");

2.0: OR :

2.1) Disjunction, , myQueryDisjunc.

Disjunction myQueryDisjunc = Restrictions.disjunction();

2.2) All OR Criterion. :

Criterion xyzName = Restrictions.ilike("xyz.name", "%"+searchStr1+"%", MatchMode.ANYWHERE);

Criterion xyzSpeciality = Restrictions.ilike("xyz.specs", "%"+searchStr1+"%", MatchMode.ANYWHERE);

Criterion xyzServices = Restrictions.ilike("xyz.services", "%"+searchStr1+"%", MatchMode.ANYWHERE);

2.3) OR Criterions myQueryDisjunc

myQueryDisjunc.add(xyzName);

myQueryDisjunc.add(xyzSpeciality);

myQueryDisjunc.add(xyzServices);

-3.0: :

3.1) Conjunction, , myQueryConjunc.

Conjunction myQueryConjunc = Restrictions.conjunction();

3.2) All AND Criterion. :

Criterion xyzLoc = Restrictions.ilike("xyz.locStr", "%"+searchStr2+"%", MatchMode.ANYWHERE);

Criterion xyzZip = Restrictions.ilike("xyz.zipStr", "%"+searchStr3+"%", MatchMode.ANYWHERE);

3.3) AND Criterions myQueryConjunc

myQueryConjunc.add(xyzLoc);

myQueryConjunc.add(xyzZip);

-4.0: myQueryDisjunc, myQueryConjunc myQueryCrit:

myQueryCrit.add(myQueryDisjunc);
myQueryCrit.add(myQueryConjunc);

-5.0: Result Trnasformer, [optional]:

myQueryCrit.setResultTransformer(
CriteriaSpecification.DISTINCT_ROOT_ENTITY);

-6.0: myQueryCrit, () .

List <myObj> allResults = myQueryCrit.list();

Step-7.0: Thats All.

+2

Source: https://habr.com/ru/post/1776974/


All Articles