@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
