[英]hibernate correct way to set default value on database side
I'm new to hibernate, and I'm looking for the correct approach to set a default value on database side.我是 hibernate 的新手,我正在寻找在数据库端设置默认值的正确方法。
I hope the DDL generated by hibernate is equivalent to this:我希望hibernate生成的DDL等价于这个:
create table SpaceGroup (
name varchar(255) not null,
isProtected boolean default FALSE not null,
primary key (name)
)
Here is my entity declaration:这是我的实体声明:
@Entity
@DynamicInsert
public class SpaceGroup {
@Id
private String name;
@ColumnDefault("FALSE")
@Column(nullable = false)
private Boolean isProtected;
}
the problem with this approach is that hibernate didn't realize there is a db default value, so when I insert object it complains I do not give a value for a not null
field:这种方法的问题是 hibernate 没有意识到有一个 db 默认值,所以当我插入 object 它抱怨我
not null
字段提供值:
org.hibernate.PropertyValueException: not-null property references a null or transient value : com.ziqi.models.SpaceGroup.isProtected
even adding a @DynamicInsert
can not solve this issue即使添加
@DynamicInsert
也不能解决这个问题
why hibernate not able to infer this field will be given a default value on database side ?为什么 hibernate 无法推断该字段将在数据库端被赋予默认值? I believe
@DynamicInsert
is not even need if I understand it correctly.如果我理解正确,我相信
@DynamicInsert
甚至都不需要。
You can simply initialize the variable and it sets that value as the default.您可以简单地初始化变量并将该值设置为默认值。 @Column(nullable = false) private Boolean isProtected = false;
@Column(nullable = false) 私有 Boolean isProtected = false;
Else, you can use columnDefinition property of the @Column annotation, for example:否则,您可以使用 @Column 注释的 columnDefinition 属性,例如:
@Column(columnDefinition=“boolean default false") private Boolean isProtected; @Column(columnDefinition="boolean default false") private Boolean isProtected;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.