SST
SST

Reputation: 2144

Search query using like with AND logic in hibernate

We are using hibernate 3.6.3.Final and MySql database in my application. I need to transform the following Mysql query to HQL using java.

select * from user where name like "%mohan%" and name like '%ram%';

How to do this logical AND operator in hibernate and java??

Upvotes: 0

Views: 466

Answers (1)

couettos
couettos

Reputation: 591

Edit :

You need to dynamically define an hql query:

String[] likes = {"foo", "bar"};

String myQuery = "select e from User e where 1=1";
for(int i=0; i<likes.length; i++){
    myQuery+= " and e.name like :"+i;
}

Query query = getSessionFactory().getCurrentSession().createQuery(myQuery);

for(int i=0; i<likes.length; i++){
    query.setParameter(i, "%"+likes[i]+"%");
}
query.list();

Note : you can use a StringBuilder to concatenate the strings

Upvotes: 1

Related Questions