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".
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.
Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
Criteria criteria= session.createCriteria(Order.class) It can be used as restrictions on the criteria query. In other words, Criterion is the object-oriented representation of the “where” clause of a SQL query. The conditions to be applied (also known as restrictions) can be provided by the Restrictions class.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With