Changing primary key id to String type in Grails

会有一股神秘感。 提交于 2019-12-30 02:02:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!