2011-03-24 86 views
21

我正在使用HQL的搜索查詢和一切工作找到,直到我到LIKE子句。不管我做什麼,它似乎都沒有正確執行LIKE子句。這是我的查詢。HQL查詢與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(); 

回答

46

字符串文字內部的參數未解析。

您需要% 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(); 
+0

怎麼樣區分大小寫。有沒有辦法讓它不區分大小寫?謝謝回覆! @axtavt – medium 2011-03-24 13:58:56

+1

在您的查詢中將'pn.name'和參數'firstName'強制轉換爲小寫 – djmj 2013-02-13 22:45:07