Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hibernate

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

like image 341
ScArcher2 Avatar asked Sep 11 '08 20:09

ScArcher2


People also ask

How does hibernate determine query criteria?

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.

How do you write join query in hibernate using criteria?

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.

What is the difference between criteria and criterion in hibernate?

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.


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

like image 88
sblundy Avatar answered Sep 29 '22 04:09

sblundy


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); 
like image 23
Rob Oxspring Avatar answered Sep 29 '22 05:09

Rob Oxspring