简体   繁体   中英

JPA cascade persistence with entity ElementCollection keys

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.

It is an error to specify both @ElementCollection and @ManyToMany at the same time. The two annotations denote different concepts of OR mapping a greater-than-one cardinality relationship.

ElementCollection is a strict aggregation or composition relationship, where elements in the collection are strictly owned by their parent object, and any interaction with the elements, like querying etc. have to be done via the parent. The multiplicity of the parent versus the elements in the collection is always one to many. The element instances can be related to only one parent at a given point in time.

ManyToMany represents a relationship between more or less independent entities, that can be queried and manipulated individually and independently of the instance declaring the property annotated with @ManyToMany . ManyToMany relationships imply that the related instances can be related to any number of other instances by other declared relationships.

I'd expect that any standards-compliant JPA implementation will either show an error or exhibit "undefined" behavior for a property annotated like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM