Saving a JPA Cascade Using ElementCollection Class Keys

I have two JPA objects, for example:

@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 relationship between Bar and Foo , so I thought it would be wise to use @ManyToMany to specify cascading for the field. However, when I try to save Bar with a pair of Foo β†’ String values ​​on 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>> 

Obviously, EclipseLink does not cascade the persistence of my Foo instances. How should I comment on fooContent to work with cascading persistence?

+7
java jpa eclipselink
source share
2 answers

Error specifying @ElementCollection and @ManyToMany at the same time. Two annotations indicate different concepts of OR, representing a power ratio other than unity.

ElementCollection is a strict relation of aggregation or composition, where the elements in the collection strictly belong to their parent, and any interaction with the elements, such as a request, etc., must be done through the parent. The set of parent elements and elements in a collection is always the same. Element instances can only be associated with one parent at a time.

ManyToMany is a relationship between more or less independent objects that can be requested and processed individually and independently of the instance declaring the property annotated with @ManyToMany . ManyToMany implies that related instances can be associated with any number of other instances by other declared relationships.

I expect that any standard JPA implementation will either show an error or exhibit "undefined" behavior for a property annotated in this way.

+4
source share

You do not need the @ManyToMany annotation @ManyToMany . ElementCollection operations ElementCollection always cascaded.

+2
source share

All Articles