简体   繁体   中英

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. 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.

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.

The exception you get is quite informative. You're trying to pass java.lang.String in place where java.lang.Long is required. Pass params.id without converting it to string:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM