问题
如何在Hibernate字段中设置默认值?
#1 热门回答(146 赞)
如果需要实际的数据库默认值,请使用columnDefinition -@Column(name = "myColumn", nullable = false, columnDefinition = "int default 100")
。请注意,字符串incolumnDefinition
是依赖于数据库的。此外,如果你选择此选项,则必须使用dynamic-insert
,soHibernate
不包括插入时具有null
值的列。否则谈论默认是无关紧要的。
但是如果你不想要数据库默认值,而只是Java代码中的默认值,那么只需初始化你的变量-private Integer myColumn = 100;
#2 热门回答(25 赞)
那么只为字段设置默认值呢?
private String _foo = "default";
//property here
public String Foo
如果他们传递一个值,那么它将被覆盖,否则,你有一个默认值。
#3 热门回答(23 赞)
你可以使用@PrePersist anotation并在pre-persist阶段设置默认值。
像这样的东西:
//... some code
private String myProperty;
//... some code
@PrePersist
public void prePersist() {
if(myProperty == null) //We set default value in case if the value is not set yet.
myProperty = "Default value";
}
// property methods
@Column(nullable = false) //restricting Null value on database level.
public String getMyProperty() {
return myProperty;
}
public void setMyProperty(String myProperty) {
this.myProperty= myProperty;
}
此方法不依赖于Hibernate下的数据库类型/版本。在持久化映射对象之前设置默认值。