JPA cascade persistence with entity ElementCollection keys

后端 未结 2 1706
别那么骄傲
别那么骄傲 2021-01-17 20:28

I have two JPA entities like this:

@Entity
class Foo {
    @Id
    private long id;
    // ...
}

@Entity
class Bar {
    @ElementCollection(targetClass = St         


        
相关标签:
2条回答
  • 2021-01-17 20:50

    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.

    0 讨论(0)
  • 2021-01-17 21:13

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

    0 讨论(0)
提交回复
热议问题