【问题标题】:Hiberate adds a column of a primitive type field as NonNullableHibernate 将原始类型字段的列添加为 Non Nullable
【发布时间】: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) 的情况下全局更改此行为?

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    也许您只是将 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;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 2017-10-15
      相关资源
      最近更新 更多