java @NotNull 在 JPA/Hibernate 中默认设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27758705/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:20:38  来源:igfitidea点击:

@NotNull on default in JPA/Hibernate

javahibernatejpanhibernate-mapping

提问by kukis

I have MySql database with several tables. Every field in each table is not nullable. That's why I am forced to use @NotNullannotation to each field in all my Java classes marked with @Entity. Do I really have to do this or is there a way to tell JPA/Hibernate to treat every field NotNullable on default?

我有几个表的 MySql 数据库。每个表中的每个字段都不能为空。这就是为什么我不得不对@NotNull所有标有@Entity. 我真的必须这样做还是有办法告诉 JPA/Hibernate 默认处理每个字段 NotNullable?

edit: I am aware of @Column(name="something", nullable=false)too. But still, it doesn't solve any problem - you have to write nullable=false

编辑:我也知道@Column(name="something", nullable=false)。但是,它仍然没有解决任何问题-您必须编写nullable=false

回答by AntonBerezin

There are no such possibility. Not Nullableconstraint is not what you always expect from a field, although it is used quite often. It is convenient when you can look at the attribute definition and tell everything out of it, without addressing to some high-level settings like "every field should be @NotNull".

没有这种可能性。Not Nullable尽管经常使用约束,但您对某个领域的期望并不总是如此。当您可以查看属性定义并从中分辨出所有内容时,这很方便,而无需处理诸如“每个字段都应该是@NotNull”之类的高级设置。

It would be rather confusing to see such entity definition with this setting hidden elsewhere.

看到这样的实体定义而此设置隐藏在其他地方会相当混乱。

And, one more thing. @NotNullannotation and @Column(name="something", nullable=false)are not the same. More details here : Confusion: @NotNull vs @Column(nullable = false)

还有一件事情。@NotNull注解和@Column(name="something", nullable=false)不一样。更多细节在这里: 混淆:@NotNull vs @Column(nullable = false)