简体   繁体   中英

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??

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM