I have two JPA entities like this:
@Entity
class Foo {
@Id
private long id;
// ...
}
@Entity
class Bar {
@ElementCollection(targetClass = String.class, fetch = FetchType.LAZY)
@MapKeyJoinColumn(name = "foo_id", referencedColumnName = "id")
@MapKeyClass(Foo.class)
@Column(name = "content")
@CollectionTable(name = "bar_foo_content",
joinColumns = @JoinColumn(name = "bar_id", referencedColumnName = "id"))
@ManyToMany(cascade = CascadeType.ALL)
private Map<Foo, String> fooContent = Maps.newHashMap();
// ...
}
As you can see, the fooContent
field forms a many-to-many relation between Bar
and Foo
, so I thought it would be appropriate to use @ManyToMany
to specify cascading for the field. However, when trying to persist a Bar
with a couple of Foo → String
values in the map, I get the following exception:
javax.persistence.RollbackException: java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: <<instance of Foo>>
Clearly, EclipseLink does not cascade the persistence of my Foo
instances. How should I annotate fooContent
to get cascaded persists working?
You don't need @ManyToMany
annotation here. Operations on ElementCollection
s are always cascaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With