【发布时间】:2016-09-21 17:07:40
【问题描述】:
我正在使用 Hibernate 添加一列。当然 hibernate.hbm2ddl.auto 属性设置为“更新”。未更改的类如下所示:
@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“如果没有指定列注释,则应用默认值。”并且可为空属性的默认值为“true”。
奇怪的是 - 我没有收到字符串或任何其他对象的错误。它只是将“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) 的情况下全局更改此行为?
【问题讨论】: