tags:

views:

751

answers:

4

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".

+5  A: 

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.

sblundy
That is perfect thanks! I finally found an example online, but I'm glad it's here for future reference.
ScArcher2
+2  A: 

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);
Rob Oxspring
I do like the syntax of creating the Disjunction and naming it or. It's a lot more readable than the other solution.
ScArcher2
+1  A: 

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)));
Geir-Tore Lindsve
A: 

Disjunction or = Restrictions.disjunction(); i tried this one or.add it's not working.

ramu