[英]Grails search on id field throws an error
I have a search page where the user should be able to search authors based on their id (GORM generated id, not a property in my domain class) or their name. 我有一个搜索页面,用户应该能够根据他们的ID(GORM生成的id,而不是我的域类中的属性)或者他们的名字来搜索作者。 The search page works fine when I search on the author's name but when trying to search on their id, I get the error below. 当我搜索作者的名字时,搜索页面工作正常但是当我们尝试搜索他们的ID时,我得到下面的错误。
Message: 信息:
java.lang.String cannot be cast to java.lang.Long
Please let me know how I can fix this. 请让我知道如何解决这个问题。
Here is my search method in the controller: 这是我在控制器中的搜索方法:
def search(Integer max) {
params.max = Math.min(max ?: 10, 100)
def authorList = Author.createCriteria().listDistinct () {
if ( params.id ) {
eq("id", "%${params.id}%")
}
if ( params.name ) {
ilike("name", "%${params.name}%")
}
respond authorList, model:[authorInstanceCount: Author.count()]
}
Replace this: 替换这个:
eq("id", "%${params.id}%")
with 同
eq("id", params.long('id'))
params.long('id')
tries to safely convert the parameter to a Long
, ie it will return null
if the conversion cannot be performed rather than throwing an exception. params.long('id')
尝试将参数安全地转换为Long
,即如果无法执行转换而不是抛出异常,它将返回null
。
The exception you get is quite informative. 您获得的例外情况非常丰富。 You're trying to pass java.lang.String
in place where java.lang.Long
is required. 你试图通过java.lang.String
,其中到位java.lang.Long
是必需的。 Pass params.id
without converting it to string: 传递params.id
而不将其转换为字符串:
eq("id", params.id) // if params.id is java.lang.Long
// or
eq("id", params.id.toLong()) // if params.id is java.lang.String
You've also missed closing curly bracket after closure of listDistinct()
method (it might be a mistake during copy-pasting). 在关闭listDistinct()
方法之后你也错过了关闭大括号listDistinct()
在复制粘贴期间可能是一个错误)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.