【问题标题】:Disable the natively generated identity value feature in grails在 grails 中禁用本机生成的标识值功能
【发布时间】:2014-05-13 04:31:30
【问题描述】:

以下是我的域类详细信息。

class Age {
    String agetype
    static constraints = {
    }

}

我正在使用 HeidiSQL。我想删除自动生成的 id 列。并将主键设置为“agetype”。我能做什么?

【问题讨论】:

    标签: grails identifier generated heidisql


    【解决方案1】:

    如果不需要默认的id,则可以在映射块内轻松自定义标识符。

    class Age {
        String agetype
    
        static mapping = {
            id name: 'agetype', 
               column: 'AGE_TYPE', // if the column name is AGE_TYPE
               generator: 'assigned' // Unique String should assigned for agetype
        }
    
        static constraints = {
            agetype bindable: true //identifiers are not bindable by default
        }
    }
    

    通过上述设置,您应该能够将 Age 创建为:

    new Age(agetype: 'Teen').save(flush: true)
    

    如果再次运行以上将通过主键冲突。

    有关根据需要自定义idcolumn 的更多详细信息,请参阅docs

    【讨论】:

    • 没有必要。可以从字段的类型推断类型。在您的情况下,我建议添加列名,因为名称不是 camelCased (ageType),如果实际列名是 AGE_TYPE,那么它不会自动推断。
    • 它不工作。 id 列仍然在那里,它是主键。我想删除 id 字段并将年龄类型作为主键。不要重命名 id 字段。
    • 确保在上述修改后重启应用后重新创建表。检查DataSource.groovy 在相关环境中是否有dbCreate = "create-drop"
    • @Sag 在这种情况下,它必须更改为“create-drop”,然后重新启动应用程序,以便删除旧表并创建一个以 agetype 作为主键的新表。
    • 我的错。我的答案中有一个错字(已纠正)。应该是 mapping 而不是 mappings 作为 static mapping = { .. }。应用重启后现在应该可以工作了。
    猜你喜欢
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多