Video in progress

What is `@ElementCollection`, and when would you use it instead of a `@OneToMany` entity?

@ElementCollection is a set of values with no id of their own that belong only to the owner (tags, phone numbers). It's stored in a separate table, but its lifecycle is entirely tied to the owner. The downside: on a change, Hibernate often deletes all the rows and writes them again.

📖 Answer

@Entity
class Customer {
    @Id @GeneratedValue Long id;

    @ElementCollection
    @CollectionTable(name = "customer_phone", joinColumns = @JoinColumn(name = "customer_id"))
    @Column(name = "phone")
    private Set<String> phones = new HashSet<>();
}

The table is customer_phone(customer_id, phone). There's no repository for phones, you never search for them on their own, and they don't live without the customer: exactly the case for @ElementCollection. An @Embeddable can be the element too (for example, Address).

By default it's LAZY and behaves like a cascade everywhere: if the customer is deleted, the phones are deleted too.

The trap to know about is updating. Elements have no id, so with a List (bag), adding one element makes Hibernate run delete from customer_phone where customer_id = ? and INSERT everything again. With a Set or with @OrderColumn it's much better: individual rows are deleted.

When I move to a @OneToMany entity:

  • the element has a life of its own (a status, a creation time, another table references it);
  • there are many elements (hundreds) and they change often;
  • you need to search or paginate over the elements separately.

For small, rarely changing values, though, @ElementCollection simplifies the code a lot.