Video in progress

Strong Middle 🌱 Spring

When is @ElementCollection convenient, and what hidden cost does it have on large collections?

@ElementCollection stores a list of plain values or an @Embeddable that has no id of its own in a separate table, which is convenient for small collections like phones or tags. But because the elements have no id, on a change Hibernate often deletes the whole collection and writes it again.

📖 Answer

@Embeddable
record Phone(String type, String number) {}   // records work in Hibernate 6.2+

@Entity
class Customer {
    @Id Long id;

    @ElementCollection
    @CollectionTable(name = "customer_phone", joinColumns = @JoinColumn(name = "customer_id"))
    private List<Phone> phones = new ArrayList<>();
}

The convenient part: there's no PhoneRepository, and the lifecycle depends entirely on Customer: if the customer is deleted, the phones go too. Ideal for 2-5 elements.

The problem is the missing id. Hibernate can't tell exactly which row changed, so if you add or remove one phone from the List:

delete from customer_phone where customer_id=?
insert into customer_phone ...   -- again for every element

For a few elements you won't notice. But if you store 5000 "viewed products" in an @ElementCollection, every change means 5000 INSERTs.

Ways to ease it:

  • use a Set (with element equals/hashCode): Hibernate can delete a single row more precisely, but the columns must not contain NULL;
  • @OrderColumn: updates by index, but gives many UPDATEs when you remove from the middle;
  • if the collection can grow, switch to a plain @OneToMany entity. It gets its own id, separate queries and pagination.

Also: @ElementCollection is LAZY by default, and if you touch each customer's phones on a list page, N+1 shows up just like with an ordinary relationship.