我有一个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/