grails - Grails:无法将整数属性添加到域类

标签 grails gorm

我有一个Grails域类,它是SQL Server上的相关数据库表。我想向现有域/表中添加一个整数类型的新属性/列jPId。这是我的代码:

class JobCode{

    int jPId // This is the new property/column I want to add.

    //Other Properties which already have corresponding columns in DB

    static mapping = {
        jPId defaultValue: 0
    }

    static constraints = {
        jPId nullable:true // tried commenting this line as well
        //Other properties
    }
}

我的数据源配置文件的数据库模式设置为“更新”,因此,我可以执行任何ALTER操作。现在,当我重新启动服务器时,我希望它在数据库中创建新的整数/数字列。但是它抛出以下错误,并且无法创建列:
ERRORorg.hibernate.tool.hbm2ddl.SchemaUpdateUnsuccessful: alter table EF_JobCode add jpid int not null
ERRORorg.hibernate.tool.hbm2ddl.SchemaUpdateALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'jpid' cannot be added to non-empty table 'EF_JobCode' because it does not satisfy these conditions.

我一无所知,因为我不知道我想念什么!我在上面的代码中给了int jPId一个默认值,并且也将其声明为nullable:true(也注释了它,因为我不确定nullable:true是否适用于基本类型)。没有任何效果,我不断看到上述错误。

最佳答案

在Hibernate / GORM中,可为空的原语没有意义。如果数据库中有一个空值,那么在Groovy / Java中零是不适当的值,因为零是有效值,并且通常与空值有很大不同,具体取决于您的业务规则。同样对于boolean / Boolean-false与null不同。始终为数字和 bool(boolean) 值指定对象类型,以允许数据库空值成为Groovy / Java空值。

此外,不要使用dbCreate='update'。添加列时,无论您在约束中指定什么内容,都将它们添加为可空值,并且您必须修复前几行以具有有效值,并将列更改为非空。此外,许多看似合理的更改将不会进行。一个例子是列加宽。即使这不会导致数据丢失,Hibernate也不会这样做。它还不会添加索引,并且还有其他相关问题。使用create-drop直到您厌倦了每次重启都会丢失数据并切换到数据库迁移,例如http://grails.org/plugin/database-migration

关于grails - Grails:无法将整数属性添加到域类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22084495/

相关文章:

hibernate - 对旧数据库使用Grails/Hibernate。如何创建缺少的功能?

servlets - 是什么触发ServletResponse使其将数据/文件发送到客户端

hibernate - 通过GORM按单向分组

grails - 如何在Grails 3的编辑 View 中修改ID列的值?

grails - 在GORM中的User域的子类上是否允许使用findByUsername

java - grails: try 抛出意外的标记: try:

grails - Grails调用服务错误

servlets - 在Grails 3应用程序中注册Servlet bean

hibernate - 如何在Grails/GORM/Hibernate中执行特定的SQL

grails - 如何使用@Build为Grails集成测试创建多种类型的测试数据