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

时间:2014-02-28 01:39:05

标签: grails gorm

我有一个Grails域类,它是SQL Server上的相关数据库表。我想在现有域/表中添加一个类型为integer的新属性/列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
    }
}

我的DataSource配置文件将DB Mode设置为'Update',这样我就能执行任何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适用于基本类型)。什么都没有用,我一直看到上面的错误。

1 个答案:

答案 0 :(得分:3)

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

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