Reputation: 714
I have a Grails domain class and it's relevant DB table on SQL Server. I want to add a new property/column jPId of type integer to the existing domain/table. Here is the code I have:
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
}
}
My DataSource config file has the DB Mode set to 'Update', so that, I can it will perform any ALTER operations. Now, when I restart the server, I expect it to create the new integer/number column in the DB. But it throws the below error and fails to create the column:
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.
I am clueless as I have no idea what am I missing ! I have given the int jPId a default value as well in the code above and also declared it as nullable:true ( commented it too as I was not sure if nullable:true is applicable to primitive types ). Nothing worked and I keep seeing the above error.
Upvotes: 0
Views: 2133
Reputation: 75681
A nullable primitive doesn't make sense in Hibernate/GORM. If there's a null value in the database, zero is not an appropriate value in Groovy/Java since zero is a valid value and often very different from null, depending on your business rules. Likewise for boolean/Boolean - false is not the same as null. Always specify the object types for numbers and booleans to allow database nulls to be Groovy/Java nulls.
Further, don't use dbCreate='update'
. When columns are added they're added as nullable regardless of what you specified in the constraints, and you have to fix the previous rows to have valid values and change the column to not-null. Further, many changes that might seem reasonable will not be done. One example is a column widening. Even though this won't result in data loss, Hibernate won't do it. It also won't add indexes, and there are other related issues. Use create-drop until you get tired of losing data every restart and switch to database migrations, e.g. http://grails.org/plugin/database-migration
Upvotes: 3