Java 无法在一对多关系休眠注释中插入空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3724719/
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
cannot insert null in one to many relationship hibernate annotation
提问by dmay
I have a class A{Set b .....} which holds references of class B as Set. It is one to many relationship. Both class have sequencer in oracle. I put cascade to all in hibernate annotations. When i save class A, it gives me error that cannot insert null B.a_id . A-id is not nullable in my database. How can i persist this relationship.
我有一个类 A{Set b .....} ,它保存类 B 作为集合的引用。这是一对多的关系。这两个类在 oracle 中都有音序器。我将级联放在休眠注释中。当我保存 A 类时,它给了我无法插入 null B.a_id 的错误。A-id 在我的数据库中不可为空。我怎么能坚持这种关系。
采纳答案by Pascal Thivent
This is a unidirectional relationship from A->B. a_id column in table B is not nullable. When hibernate tries to save class B, it not able to find value for a_id.
这是从 A->B 的单向关系。表 B 中的 a_id 列不可为空。当hibernate 尝试保存B 类时,它无法找到a_id 的值。
Well, did you try to make the JoinColumn
non nullable
?
那么,你有没有尝试制作JoinColumn
非nullable
?
@OneToMany
@Cascade({CascadeType.ALL})
@JoinColumn(name="A_ID", nullable=false)
private Set<B> b;
See also
也可以看看
- Hibernate Core Reference Guide
- Hibernate 核心参考指南
回答by Jos
I ran into the same problem and solved it by using the mappedBy attribute of the @OneToMany annotation in Class A:
我遇到了同样的问题,并通过使用 A 类中的 @OneToMany 注释的 mappingBy 属性解决了它:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "m_a")
private Set<B> b;
Here, m_a is the field in Class B that refers to Class A:
这里,m_a 是 B 类中引用 A 类的字段:
@JoinColumn(name = "aId", nullable = false)
@ManyToOne
private A m_a;
This way, the @JoinColumn is only specified in one place, no duplicated code.
这样,@JoinColumn 只在一处指定,没有重复的代码。