JPA: When to choose Multivalued Association vs. Element Collection Mapping

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 ElementCollection mapping can be
used to define a collection of
Embeddable objects. This is not a
typical usage of Embeddable objects as
the objects are not embedded in the
source object’s table, but stored in a
separate collection table. This is
similar to a OneToMany, except the
target object is an Embeddable instead
of an Entity. This allows collections
of simple objects to be easily
defined, without requiring the simple
objects to define an Id or ManyToOne
inverse mapping. ElementCollection can
also override the mappings, or table
for their collection, so you can have
multiple entities reference the same
Embeddable class, but have each store
their dependent objects in a separate
table.

The limitations of using an
ElementCollection instead of a
OneToMany is that the target objects
cannot be queried, persisted, merged
independently of their parent object.
They are strictly privately-owned
(dependent) objects, the same as an
Embedded mapping. Their is no cascade
option on an ElementCollection, the
target objects are always persisted,
merged, removed with their parent.
ElementCollection still can use a
fetch type and defaults to LAZY the
same as other collection mappings.

See also

  • Embeddables (Aggregates, Composite or Component Objects)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)