Java @ManyToOne(optional=false) 和@Column(nullable=false) 有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3331907/
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
What is the difference between @ManyToOne(optional=false) vs. @Column(nullable=false)
提问by Truong Ha
In JPA, I am confused when to use the attribute optional=false
and the annotation @Column(nullable=false)
. What is the difference?
在 JPA 中,我对何时使用 attributeoptional=false
和 annotation感到困惑@Column(nullable=false)
。有什么不同?
采纳答案by Affe
@Column(nullable=false)
is an instruction for generating the schema. The database column generated off the class will be marked not nullable in the actual database.
@Column(nullable=false)
是生成模式的指令。从类生成的数据库列将在实际数据库中标记为不可为空。
optional=false
is a runtime instruction. The primary functional thing it does is related to Lazy Loading. You can't lazy load a non-collection mapped entity unless you remember to set optional=false (because Hibernate doesn't know if there should be a proxy there or a null, unless you tell it nulls are impossible, so it can generate a proxy.)
optional=false
是运行时指令。它所做的主要功能与延迟加载有关。你不能延迟加载一个非集合映射的实体,除非你记得设置 optional=false(因为 Hibernate 不知道那里是否应该有一个代理或一个空值,除非你告诉它空值是不可能的,所以它可以生成代理。)
回答by O.Badr
Both is used to prevent a null value, but if you mind that null should be blocked in ...
两者都用于防止空值,但如果您介意应该在 ...
The databaselayer (and you want to generate the schema using JPA) --> use @Column(nullable=false)
该数据库层(你想生成使用JPA的模式) - >使用@Column(nullable=false)
The runtime(and before contacting the database)--> use optional=false
(much faster than the first checking).
在运行时(和数据库接触之前) - >使用optional=false
(比第一检查快得多)。
If you want both abilities, use them both.
如果您想要这两种能力,请同时使用它们。