java 休眠默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17882103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate default values
提问by Vojtěch
Is there a way with hibernate to define default values for each field and for the sake of database size write null instead of these default values?
有没有办法让 hibernate 为每个字段定义默认值,并且为了数据库大小写 null 而不是这些默认值?
For inst. let's say the default value for String is "". I would like Hibernate to:
对于inst。假设字符串的默认值为“”。我希望 Hibernate 能够:
- return "" for each field, that has NULL in database.
- write NULL to database, when I try to write ""
- 为每个字段返回“”,在数据库中为 NULL。
- 将 NULL 写入数据库,当我尝试写入“”时
Of course, I can write thousands of Getters and Setters, but can it be done automatically?
当然,我可以写上千个Getter和Setter,但是可以自动完成吗?
回答by But I'm Not A Wrapper Class
If you want a real database default value, use columnDefinition - @Column(name = “myColumn”, nullable = false, columnDefinition = “int default 100"). 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.
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;
如果你想要一个真正的数据库默认值,使用 columnDefinition - @Column(name = “myColumn”, nullable = false, columnDefinition = “int default 100”。注意 columnDefinition 中的字符串是数据库相关的。如果你选择这个选项, 你必须使用动态插入,所以 Hibernate 不会在插入时包含空值的列。否则谈论默认是无关紧要的。
但是,如果您不想要数据库默认值,而只是 Java 代码中的默认值,只需像这样初始化您的变量 - private Integer myColumn = 100;
Source:
来源:
How to set default value in Hibernate
Of course, instead of using:
当然,而不是使用:
columnDefinition = “int default 100"
Try something like:
尝试类似:
columnDefinition = “TEXT default `default_text`"
I'm not sure if that's syntaically correct, but check these out:
我不确定这在语法上是否正确,但请查看以下内容:
Text Field using Hibernate Annotation
回答by varun
You may implement such thing using field getters, Its simple and will serve the purpose.
您可以使用字段 getter 来实现这样的事情,它很简单并且可以达到目的。

