2014-04-02 33 views
1

由於我無法使用Hibernate createCriteria實現所需的查詢,因此我堅持使用常見的Mysql連接。但是,當我使用參數化查詢時,由於某種原因,部分查詢失敗。 返回數據源連接的代碼是使用類似grails準備語句時引發的異常

def getSqlInstance(){    
def conn = dataSource.connection 
Sql sql = new Sql(conn) 
return sql; 
} 

當我使用的一些變化查詢以下形式

def conn = getSqlInstance(); 
def result = conn.rows("select distinct u.user_id from user_role u inner join (select id from role where authority like %:roles%)r on u.role_id = r.id",params) 

我得到下面的異常

你有一個錯誤你的SQL語法;請檢查與您的MySQL服務器版本相對應的手冊,以找到在第1行的'%')r on u.role_id = r.id'處使用的正確語法。Stacktrace如下: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException :您的SQL語法錯誤;檢查對應於你的MySQL服務器版本的行u.role_id = r.id」附近使用「%」)R正確的語法手冊1

有人可以幫助與此請

+0

該查詢按預期執行如果我使用「=」,而不是或「喜歡」 – thickGlass

+0

我可以使用來糾正這個錯誤''%':角色'%''但是查詢仍然會在使用** <'&** ** – thickGlass

回答

1

另一種解決方案所需的結果是基於SQL的

def result = conn.rows("select distinct u.user_id from user_role u inner join 
         (select id from role where authority like 
         concat('%',:roles,'%')) r on u.role_id = r.id", 
         params) 
1

我想出了我做錯了什麼,我不得不將%作爲要傳遞的地圖的一部分。我使用

`def result = conn.rows("select distinct u.user_id from user_role u inner join (select id from role where authority like ?)r on u.role_id = r.id","%"+role+"%")`