liveBook · Manning

@ElementCollection

As explained in Java Persistence with Spring Data and Hibernate epub

@ElementCollection is a Jakarta Persistence annotation that maps a collection of basic or embeddable value types belonging to an entity.

@ElementCollection maps values owned by an entity rather than independent entities. For image filenames, an Item can hold a Set<String> while the filenames live in a separate IMAGE table. The database stores filenames, not the image files themselves. section 8.1.4

Mapping image filenames

Declare the field as `@ElementCollection private Set<String> images = new HashSet<>();`. Use `@CollectionTable(name = "IMAGE", joinColumns = @JoinColumn(name = "ITEM_ID"))` to name the table and its link to Item, and `@Column(name = "FILENAME")` to name the value column. Without the latter two annotations, Hibernate uses default schema names. The example table has a composite primary key of ITEM_ID and FILENAME: one item cannot contain the same filename twice, and image order is not stored. A Spring Data JPA query using `inner join fetch i.images` can retrieve the collection with its Item. section 8.1.4

Choose the element type to match the ownership you need:

  • Use basic values, such as String filenames, when the collection needs no separate object with its own lifecycle. section 8.1.4
  • Use @Embeddable components when each element has several properties but depends fully on its owner. For bids owned by an Item, this is an alternative to @OneToMany entity bids with cascading or orphan removal; shared references must be avoided. section 8.3.3
  • Use an embeddable link component for a richer association. A Category can own components that each refer to an Item and a User and record when the link was added. Adding or removing a component creates or breaks the link without extra cascading settings. section 9.3.3
Path: manytomany-ternary/src/main/java/com/manning/javapersistence
 /ch09/manytomany/ternary/Category.java
 
@Entity
public class Category {
    // . . .
    @ElementCollection
    @CollectionTable(
        name = "CATEGORY_ITEM",
        joinColumns = @JoinColumn(name = "CATEGORY_ID")
    )
    private Set<CategorizedItem> categorizedItems = new HashSet<>();
    //  . . .
}

The Category mapping shows @ElementCollection on a Set of embeddable link components, with @CollectionTable naming the link table and owner join column. section 9.3.3

Embeddable elements cannot provide shared, bidirectional navigation; query from the other side instead. Check generated schemas for embeddable collections, too: in the shown Hibernate mapping, properties marked `nullable=false` become part of the composite primary key. Using `@NotNull` on other required properties avoids that key effect but does not generate their SQL NOT NULL constraints, so those constraints need manual attention. section 9.3.3

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Works through Java mappings, collection tables, lifecycle choices, and a Hibernate schema caveat, without detailing the annotation's full API.
Examples
Uses an Item's image-filename set and a Category's collection of link components referring to Item and User.
What it assumes
Assumes familiarity with Java entity fields, annotations, and relational tables when comparing collection and association mappings.
What you can do after
Build it from scratch as a basic-value or embeddable collection, then assess ownership and generated-schema consequences.
How it connects
Connects @Embeddable, @CollectionTable, @OneToMany, cascading, orphan removal, and @ManyToOne through alternative collection and association mappings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.