问题
My Grails 2.0 app has a User domain object defined:
class User {
static mapping = {
table "dt_user"
columns {
id column:'user_id', generator:'assigned', type:'string'
}
}
When I try to save a new User in my BootStrap file like so:
def user = new User(id: "smith").save(failOnError:true)
I get the following error:
| Error 2012-01-13 10:09:42,659 [main] ERROR property.BasicPropertyAccessor - IllegalArgumentException in class: User, setter method of property: id
| Error 2012-01-13 10:09:42,660 [main] ERROR property.BasicPropertyAccessor - expected type: java.lang.Long, actual value: java.lang.String
I also tried changing the User class to this:
class User {
static mapping = {
table "dt_user"
columns {
id column:'user_id', generator:'assigned', type:'string', name:'id'
}
}
String id
}
which made the above errors go away. However I found that this resulted in ids being generated automatically, completely ignoring the generator: 'assigned'
clause.
What am I doing wrong here?
回答1:
Looks like wrapping it in the columns
block is the culprit. This may have been required at some point (before my time) but it's been optional as long as I've used Grails and apparently is now broken. But you can just declare column mappings directly:
class User {
String id
static mapping = {
table "dt_user"
id column: 'user_id', generator: 'assigned'
}
}
As long as the field is declared as a String and it's configured as assigned
it will work; there's no need to tell GORM it's a String, it can figure that out.
来源:https://stackoverflow.com/questions/8856336/changing-primary-key-id-to-string-type-in-grails