在 Grails 中将主键 id 更改为 String 类型 [英] Changing primary key id to String type in Grails

查看:25
本文介绍了在 Grails 中将主键 id 更改为 String 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Grails 2.0 应用定义了一个用户域对象:

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'
    }
}

当我尝试在我的 BootStrap 文件中保存一个新用户时:

When I try to save a new User in my BootStrap file like so:

def user = new User(id: "smith").save(failOnError:true)

我收到以下错误:

| 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

我也尝试将 User 类更改为:

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 
}

使上述错误消失.但是我发现这会导致自动生成 id,完全忽略了 generator: 'assigned' 子句.

which made the above errors go away. However I found that this resulted in ids being generated automatically, completely ignoring the generator: 'assigned' clause.

我在这里做错了什么?

推荐答案

看起来将它包装在 columns 块中是罪魁祸首.这在某些时候(在我之前)可能是必需的,但只要我使用过 Grails,它就一直是可选的,而且现在显然已损坏.但是你可以直接声明列映射:

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'
   }
}

只要该字段被声明为一个字符串并且它被配置为assigned,它就会起作用;不需要告诉 GORM 它是一个字符串,它可以弄清楚.

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.

这篇关于在 Grails 中将主键 id 更改为 String 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆