为什么hibernate在一个表中保存两个@OneToMany列表? [英] Why does hibernate save two @OneToMany lists in one table?

查看:217
本文介绍了为什么hibernate在一个表中保存两个@OneToMany列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有以下使用Hibernate和JPA的简化代码:

  @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

code>关联。您需要首先确定您的关联是单向还是双向的。



如果您的关联是单向的,那么您需要使用 @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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆