我正在添加一个Hibernate列。当然hibernate.hbm2ddl.auto属性设置为" update"。不变的类看起来像这样:
@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注释,则默认值适用。" nullable属性的默认值为" true"。
奇怪的是 - 我没有得到String或任何其他Object的错误。它只是放置" null"在旧行。另外 - 如果我专门将nullable设置为true,我不会得到基本类型的错误。
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)?
答案 0 :(得分:0)
也许您只是将newValue声明为Integer
而不是int
?这将默认为nullable=true
:
@Entity
public class Foo {
@Id
@GeneratedValue
private int id;
private Integer newValue;
public Foo() {
}
}
原始类型的 nullable=true
并不真正有意义,因为它不具有null
值。你不能写:int a = null;