Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Hibrate将基元类型字段的列添加为不可为空_Java_Hibernate - Fatal编程技术网

Java Hibrate将基元类型字段的列添加为不可为空

Java Hibrate将基元类型字段的列添加为不可为空,java,hibernate,Java,Hibernate,我正在添加一个带有Hibernate的列。当然,hibernate.hbm2ddl.auto属性设置为“更新”。未更改的类如下所示: @Entity public class Foo { @Id @GeneratedValue private int id; public Foo() { } } @Entity public class Foo { @Id @GeneratedValue private int id;

我正在添加一个带有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() {

    }
}
更改的类如下所示:

@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.
我想知道为什么,因为根据@columnapi,“如果没有指定列注释,则应用默认值。”而nullable属性的默认值是“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)?

也许您只是将newValue声明为
Integer
,而不是
int
?默认情况下,这将使其
nullable=true

@Entity
public class Foo {
    @Id
    @GeneratedValue
    private int id;

    private Integer newValue;

    public Foo() {

    }
}
基本类型的
nullable=true
实际上没有意义,因为不能有
null
值。不能写入:
inta=null