I would like to better understand the differences between
(1) a traditional Multivalued Relationship/Association
@Entity -> @OneToMany -> @Entity and
(2) the JPA2 Collection of Embeddable (and basic) Types
@Entity -> @ElementCollection -> @Embeddable I see the syntactical differences, but wonder whether there are also performance implications. Under the hood, the database implementation looks very similar.
Intuitively, I would typically use the @ElementCollection for composition scenarios. But even that feels very similar like CascadeType=DELETE.
Am I missing the essence here? Is one more efficient than the other for certain purposes?
Thank you, J.
Intuitively, I would typically use the @ElementCollection for composition scenarios. But even that feels very similar like CascadeType=DELETE
They are similar, with some slight differences. The ElementCollection page from the Java Persistence wikibook summarizes it pretty well:
Emdedded Collections
An
ElementCollectionmapping can be used to define a collection ofEmbeddableobjects. This is not a typical usage ofEmbeddableobjects as the objects are not embedded in the source object's table, but stored in a separate collection table. This is similar to aOneToMany, except the target object is anEmbeddableinstead of anEntity. This allows collections of simple objects to be easily defined, without requiring the simple objects to define anIdorManyToOneinverse mapping.ElementCollectioncan also override the mappings, or table for their collection, so you can have multiple entities reference the sameEmbeddableclass, but have each store their dependent objects in a separate table.The limitations of using an
ElementCollectioninstead of aOneToManyis that the target objects cannot be queried, persisted, merged independently of their parent object. They are strictly privately-owned (dependent) objects, the same as anEmbeddedmapping. Their is nocascadeoption on anElementCollection, the target objects are always persisted, merged, removed with their parent.ElementCollectionstill can use a fetch type and defaults toLAZYthe same as other collection mappings.
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