我正在使用Hibernate添加一列。當然hibernate.hbm2ddl.auto屬性設置爲「update」。不變類看起來是這樣的:Hiberate將原始類型字段的列添加爲NonNullable
@Entity
public class Foo {
@Id
@GeneratedValue
private int id;
public Foo() {
}
}
更改類看起來是這樣的:
@Entity
public class Foo {
@Id
@GeneratedValue
private int id;
private int newValue = 0;
public Foo() {
}
}
當我加入一個基本類型的列,像上面我獲得以下錯誤:
Caused by: ERROR 42601: In an ALTER TABLE statement, the column 'NEWVALUE' has been specified as NOT NULL and either the DEFAULT clause was not specified or was specified as DEFAULT NULL.
我想知道爲什麼,因爲根據@Column API「如果沒有指定Column註釋,默認值適用」和默認值fo可空屬性爲「true」。
奇怪的是 - 我沒有得到字符串或任何其他對象的錯誤。它只是在舊行中放置「null」。另外 - 如果我專門設置爲空,我不會收到原始類型的錯誤。
private String newValue = "0"; //Gives no error
private String newValue; //Gives no error
@Column (nullable = true)
private int newValue; // Gives no error
結論是,hibernate在默認情況下將基元的列設置爲不可空。當我添加一列時,有一些遺留行,它們對新列沒有值,這會引發錯誤。
問題是,如果我可以在全球範圍內改變某個地方的這種行爲,而無需每次都設置@Column(nullable = true)?