我正在使用HQL进行搜索查询,一切正常,直到我找到LIKE子句。无论我做什么,似乎都没有正确执行LIKE子句。这是我的询问。
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();
答案 0 :(得分:52)
字符串文字内的参数未解析。
您需要将%
s添加到带字符串连接的参数值 - 在程序端
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();
或在数据库方面:
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();
答案 1 :(得分:0)
我们可以使用多个concat解决此问题。
SELECT pn.personId FROM PersonName pn WHERE pn.personNameType = 'FIRST' AND pn.name LIKE concat(concat('%", firstName), '%')