保存双向多对多 [英] Saving bidirectional ManyToMany

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

问题描述

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

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.

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

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