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();
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.
Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.
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();
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), '%')
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