JPA cascade persistence with entity ElementCollection keys

时光总嘲笑我的痴心妄想 提交于 2019-12-23 07:56:09

问题


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?


回答1:


You don't need @ManyToMany annotation here. Operations on ElementCollections are always cascaded.




回答2:


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.



来源:https://stackoverflow.com/questions/19428351/jpa-cascade-persistence-with-entity-elementcollection-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!