Java JPA 中的 @Basic(optional = false) 与 @Column(nullable = false)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2899073/
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
@Basic(optional = false) vs @Column(nullable = false) in JPA
提问by joaosavio
What's the difference between @Basic(optional = false)
and @Column(nullable = false)
in JPA persistence?
JPA 持久性@Basic(optional = false)
和@Column(nullable = false)
JPA 持久性之间有什么区别?
采纳答案by Pascal Thivent
Gordon Yorke (EclipseLink Architecture Committee Member, TopLink Core Technical Lead, JPA 2.0 Expert Group Member) wrote a good answer on this topic so instead of paraphrasing him, I'll quote his answer:
Gordon Yorke(EclipseLink 架构委员会成员、TopLink 核心技术负责人、JPA 2.0 专家组成员)在这个主题上写了一个很好的答案,所以我不会解释他,而是引用他的回答:
The difference between
optional
andnullable
is the scope at which they are evaluated. The definition of 'optional
' talks about property and field values and suggests that this feature should be evaluated within the runtime. 'nullable
' is only in reference to database columns.If an implementation chooses to implement
optional
then those properties should be evaluated in memory by the Persistence Provider and an exception raised before SQL is sent to the database otherwise when using 'updatable=false
' 'optional
' violations would never be reported.
optional
和 之间的区别nullable
是它们被评估的范围。'optional
'的定义涉及属性和字段值,并建议应在运行时评估此功能。'nullable
' 仅参考数据库列。如果实现选择实现,
optional
那么持久性提供程序应在内存中评估这些属性,并在将 SQL 发送到数据库之前引发异常,否则永远不会报告使用updatable=false
“ ”optional
”违规时的情况。
回答by Ray Hulha
So I tried the @Basic(optional=false) annotation using JPA 2.1 (EclipseLink) and it turns out the annotation is ignored in actual usage (at least for a String field). (e.g. entityManager.persist calls).
所以我使用 JPA 2.1 (EclipseLink) 尝试了 @Basic(optional=false) 注释,结果在实际使用中忽略了注释(至少对于 String 字段)。(例如 entityManager.persist 调用)。
So I went to the specification and read up about it.
Here is what the spec has to say:
http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-oth-JSpec/
所以我去了规范并阅读了它。以下是规范的内容:http:
//download.oracle.com/otndocs/jcp/persistence-2.0-fr-oth-JSpec/
Basic(optional): Whether the value of the field or property may be null. This is a hint and is disregarded for primitive types; it may be used in schema generation.
Basic(可选):字段或属性的值是否可以为空。这是一个提示,对于原始类型不予考虑;它可以用于模式生成。
So I think this sentence explains the real use case for Basic(optional) it is used in schema generation. (That is: when you generate CREATE TABLE SQL from Java Entity classes. This is something Hibernate can do for example.)
所以我认为这句话解释了在模式生成中使用的 Basic(optional) 的真实用例。(也就是说:当您从 Java 实体类生成 CREATE TABLE SQL 时。例如,这是 Hibernate 可以做的事情。)