保存双向ManyToMany [英] Saving bidirectional ManyToMany

查看:120
本文介绍了保存双向ManyToMany的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个以下列方式注释的实体类

I have two entity classes annotated in the following way

@Entity
class A {
   @ManyToMany(mappedBy="A", cascade=CascadeType.ALL)
   private List<B> b;
 ..
}

@Entity
class B {
   @ManyToMany(cascade=CascadeType.ALL)
   private List<A> a;
 ..
}

如果我存储类'B的实例',关系存储在数据库中,类'A'中的getter将返回B的正确子集。但是,如果我对'A'中的B列表进行更改,则更改不会存储在数据库中?

If I store an instance of the class 'B', the relations are stored in the database and the getter in class 'A' will return the correct subset of B's. However, if I make changes to the list of Bs in 'A', the changes are not stored in the database?

我的问题是,我怎样才能这样做任何一个类中的更改都级联到另一个类?

My question is, how can I make it so that changes in either class are "cascaded" to the other class?

编辑:我尝试了删除mappedBy参数和定义JoinTable(和列)的不同变体),但我一直无法找到正确的组合。

I've tried different variations of removing the mappedBy-parameter and defining a JoinTable (and columns), but I've been unable to find the correct combination.

推荐答案

最短的答案似乎是你做不到而且它使得感。在双向多对多关联中,一方必须是主方并且用于持久更改底层连接表。由于JPA不会维护关联的两个方面,因此最终可能会出现一旦存储在数据库中就无法重新加载的内存情况。
示例:

The shortest answer seems to be you cannot and it makes sense. In a bidirectional many-to-many association one side must be master and is used to persist changes to the underlying join table. As JPA will not maintain both side of the association, you could end up with a memory situation that could not be reloaded once stored in the database. Example:

A a1 = new A();
A a2 = new A();
B b = new B();
a1.getB().add(b);
b.getA().add(a2);

如果此状态可以保留,您最终会在连接表中输入以下条目:

If this state could be persisted, you would end up with the following entries in the join table:

a1_id, b_id
a2_id, b_id

但在加载时,JPA如何知道你打算只让b知道a2而不是a1?那个不应该知道b的a2呢?

But upon loading, how would JPA know that you intended to only let b know about a2 and not a1 ? and what about a2 that should not know about b ?

这就是为什么你必须自己维护双向关联(并使上面的例子无法达到,即使在内存)和JPA只会根据其中一方的状态而持续存在。

This is why you have to maintain the bidirectional association yourself (and make the above example impossible to get to, even in memory) and JPA will only persist based on the state of one side of it.

这篇关于保存双向ManyToMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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