Search code examples
grailsgroovygrails-orm

ID type mismatch when trying to get


Was just testing my code earlier this morning, and found something I cannot seems to resolve.

My SKU class has a custom ID generator(assinged) to take a String:

static mapping = {
    id generator: 'assigned', name: 'sku'
}

I created a SKU object with ID: "1234445" (Normally my SKU id is a mixture of dashes letters and numbers, but just for testing purposes I used a number as String)

Now whenever I try to do an SKU.get("1234445"), I get the following Error:

Provided id of the wrong type

Expected: class java.lang.String, got class java.lang.Long

Obviously I provided a String, somehow it's treating it as a Long when .get is performed, hence causing the error.

Any ideas on how to resolve this besides not using a String that looks like a number for SKU.id (Sku.sku in my case)?


Solution

  • Use String id instead of String sku, if want to use SKU.get("123445")

    class SKU {
        String id
        static mapping = {
            id generator: 'assigned'
        }
    }
    
    def newSku = new SKU()
    newSku.id = '123445'
    newSku.save(flush: true)
    
    println SKU.get("123445")
    

    If you need to use sku specifically as the identifier then use

    SKU.findBySku("123445")
    

    with the mapping you have right now (as mentioned in the question).