How do you "OR" criteria together when using a criteria query with hibernate?

Viewed 104994

I'm trying to do a basic "OR" on three fields using a hibernate criteria query.

Example

class Whatever{
 string name;
 string address;
 string phoneNumber;
}

I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".

8 Answers

You want to use Restrictions.disjuntion(). Like so

session.createCriteria(Whatever.class)
    .add(Restrictions.disjunction()
        .add(Restrictions.eq("name", queryString))
        .add(Restrictions.eq("address", queryString))
        .add(Restrictions.eq("phoneNumber", queryString))
    );

See the Hibernate doc here.

Assuming you have a hibernate session to hand then something like the following should work:

Criteria c = session.createCriteria(Whatever.class);
Disjunction or = Restrictions.disjunction();
or.add(Restrictions.eq("name",searchString));
or.add(Restrictions.eq("address",searchString));
or.add(Restrictions.eq("phoneNumber",searchString));
c.add(or);

Just in case anyone should stumble upon this with the same question for NHibernate:

ICriteria c = session.CreateCriteria(typeof (Whatever))
    .Add(Expression.Disjunction()
        .Add(Expression.Eq("name", searchString))
        .Add(Expression.Eq("address", searchString))
        .Add(Expression.Eq("phoneNumber", searchString)));

This is what worked for me for an OR condition, that too with an IN condition and not the answer up-voted most on this discussion:

criteria.add( Restrictions.or(
                    Restrictions.eq(ch.getPath(ch.propertyResolver().getXXXX()), "OR_STRING"),
                        Restrictions.in(ch.getPath(ch.propertyResolver().getYYYY()), new String[]{"AA","BB","CC"})
                    ));

Resulting Query:

  and (
            this_.XXXX=? 
            or this_.YYYY in (
                ?, ?, ?
            )
        ) 

If someone is using CriteriaQuery instead of Criteria, you can put all your expressions in a Predicate list and put a OR by predicates size like this:

List<Predicate> predicates = new ArrayList<>();
if (...) {
  predicates.add(...);
}

criteriaQuery.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
Related