Harry Muscle
Harry Muscle

Reputation: 2377

Grails: TypeMismatchException - Provided id of the wrong type - Expected: class java.lang.Integer, got class java.lang.Long

I have the following domain model class:

class UserSettings
{
  static mapping = {
    id name: 'pid', generator: 'assigned'
  }

  Integer pid
}

And I'm trying to get an instance of the user settings like this:

UserSettings.get(new Integer("12345"))

However, I get the following error

Provided id of the wrong type for class UserSettings. Expected: class java.lang.Integer, got class java.lang.Long

I've also tried passing it a basic int type, and I get the same error. It's like somewhere along the way the "get" method casts my Integer into a Long. Changing the type of the "pid" property in the UserSettings domain class to Long fixes things, however, since I'm integrating with a legacy database, I need the ID to be an Integer not a Long.

Upvotes: 2

Views: 4975

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75671

In general don't use new Integer, new Long, new Boolean, etc. Use literals and let Java autobox the values for you. If you look at the source of the Integer and Long you'll see that their valueOf methods (which are used when autoboxing) keep a cache of 256 of the smaller values. This won't result in a significant savings but is a good idea, and since you get the same thing with the constructor and valueOf, it's best to always use valueOf.

Further, GORM will convert the input id to the correct type for the domain class. This is why SomeDomainClass.get(params.id) works in controllers - even though all params are strings, GORM can easily convert from a string to a numeric type.

So your best bet here is to work less:

UserSettings.get("12345")

Upvotes: 2

Related Questions