Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

java - Saving bidirectional 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;
 ..
}

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?

EDIT: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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 ?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...