Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL query with LIKE having issues

Tags:

hibernate

hql

I am working on a search query using HQL and everything works find until I get to the LIKE clause. No matter what I do it does not seem to execute the LIKE clause properly. Here is my query.

String QUERY = "FROM Person as p WHERE p.createUser = : createUser       AND p.personId in (SELECT pn.personId FROM PersonName pn WHERE pn.personNameType = 'FIRST' AND pn.name LIKE '%:firstName%')";  (List<Person>)session.createQuery(QUERY).setString("createUser", createUser).setString("firstName", firstName).list(); 
like image 914
medium Avatar asked Mar 24 '11 13:03

medium


People also ask

How do you use like clause in HQL?

Well, LIKE operator is usually used with textual data i.e. with VARCHAR or CHAR columns, and you have numeric id column (INTEGER). Maybe you could try to map id field also as string and use that field in query. This may or may not work depending on your database engine.

Can we use select * in HQL?

Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.


2 Answers

Parameters inside string literals are not resolved.

You need to add %s to parameter values with string concatenation - either at the program side

String QUERY = "FROM Person as p WHERE p.createUser = : createUser       AND p.personId in " +      "(SELECT pn.personId FROM PersonName pn " +       "WHERE pn.personNameType = 'FIRST' " +       "AND pn.name LIKE :firstName)";  (List<Person>)session.createQuery(QUERY)     .setString("createUser", createUser)     .setString("firstName", "%" + firstName + "%").list(); 

or at the database side:

String QUERY = "FROM Person as p WHERE p.createUser = : createUser       AND p.personId in " +      "(SELECT pn.personId FROM PersonName pn " +       "WHERE pn.personNameType = 'FIRST' " +       "AND pn.name LIKE CONCAT('%', :firstName, '%'))";  (List<Person>)session.createQuery(QUERY)     .setString("createUser", createUser)     .setString("firstName", firstName).list(); 
like image 174
axtavt Avatar answered Sep 19 '22 12:09

axtavt


we can use multiple concat to resolve this issue.

SELECT pn.personId FROM PersonName pn WHERE pn.personNameType = 'FIRST' AND pn.name LIKE concat(concat('%', :firstName), '%') 
like image 36
MR AND Avatar answered Sep 18 '22 12:09

MR AND