为什么hibernate在一个表中保存两个@OneToMany列表? [英] Why does hibernate save two @OneToMany lists in one table?
问题描述
@Entity
class C {
@Id @GeneratedValue public long id;
}
@MappedSuperclass
抽象类A {
@Id @GeneratedValue public long id;
@OneToMany(cascade = CascadeType.ALL)
public List< C>列表1;
@OneToMany(cascade = CascadeType.ALL)
public List< C>列表2;
}
@Entity
class B extends A {}
使用PostgreSQL数据库,这会导致带有列的 b_c
列
b_id | list1_id | list2_id
现在,试图保存任何 B
导致以下异常:
org.postgresql.util.PSQLException:FEHLER:NULL-Wert in Spaltelist2_idverletzt Not-无约束
详细信息:Fehlgeschlagene Zeileenthält(779,827,null)。
大致转换为
NULL-Value in列list2_id违反了非空约束。内容:(770,827,null)
为什么会发生这种情况,我该如何避免它? <
将列表合并成一个不是一个选项。使用集合不会改变任何东西。
这是因为单向 @OneToMany
如果您的关联是单向的,那么您需要使用 @JoinColumn
来修复额外的连接表问题。如果您的关联是双向的,那么您将依靠 @ManyToOne
端传播所有实体状态更改,并使用 mappedBy
放在 @OneToMany
一边。你可以找到关于 @OneToMany
关联这里。
Imagine having following simplified code using Hibernate and JPA:
@Entity
class C {
@Id @GeneratedValue public long id;
}
@MappedSuperclass
abstract class A {
@Id @GeneratedValue public long id;
@OneToMany(cascade = CascadeType.ALL)
public List<C> list1;
@OneToMany(cascade = CascadeType.ALL)
public List<C> list2;
}
@Entity
class B extends A { }
Using a PostgreSQL database, this leads to a table b_c
with columns
b_id | list1_id | list2_id
Now, trying to persist any B
leads to following exception:
org.postgresql.util.PSQLException: FEHLER: NULL-Wert in Spalte „list2_id" verletzt Not-Null-Constraint
Detail: Fehlgeschlagene Zeile enthält (779, 827, null).
Which roughly translates to
NULL-Value in column "list2_id" violates Non-Null-Constraint. Contents: (770, 827, null)
Why does this happen and how can I avoid it?
Merging the lists into one is not an option. Using Sets instead does not change anything.
This is happening because of the unidirectional @OneToMany
association. You need to first determine if your association is unidirectional or bidirectional.
If your association is unidirectional then you need to use @JoinColumn
to fix the extra join table problem. If your association is bidirectional, then you will rely on the @ManyToOne
side to propagate all entity state changes, with the use of mappedBy
on the @OneToMany
side. You can find good explanation about different ways of @OneToMany
association here.
这篇关于为什么hibernate在一个表中保存两个@OneToMany列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!