如何使用 Hibernate 设置默认实体属性值 [英] How to set a default entity property value with Hibernate
问题描述
如何在 Hibernate 字段中设置默认值?
How do I set a default value in Hibernate field?
推荐答案
如果你想要一个真正的数据库默认值,使用columnDefinition
:
If you want a real database default value, use columnDefinition
:
@Column(name = "myColumn", nullable = false, columnDefinition = "int default 100")
请注意,columnDefinition
中的字符串依赖于数据库.此外,如果您选择此选项,则必须使用 dynamic-insert
,因此 Hibernate
不会在插入时包含具有 null
值的列.否则谈论默认是无关紧要的.
Notice that the string in columnDefinition
is database dependent. Also if you choose this option, you have to use dynamic-insert
, so Hibernate
doesn't include columns with null
values on insert. Otherwise talking about default is irrelevant.
但是如果你不想要数据库默认值,而只是你的 Java 代码中的一个默认值,只需像这样初始化你的变量 - private Integer myColumn = 100;
But if you don't want database default value, but simply a default value in your Java code, just initialize your variable like that - private Integer myColumn = 100;
这篇关于如何使用 Hibernate 设置默认实体属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!