Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Entity Mapping

Element Collections and Maps

Store collections of basic values or embeddables with @ElementCollection, @CollectionTable, @OrderColumn and @MapKeyColumn, and see the SQL tables behind them.

Sometimes an entity owns a small list of simple values: tags on a post, phone numbers of a customer, a map of settings. Creating a full entity for each would be overkill. @ElementCollection stores such collections in a separate table that has no identity of its own and is completely controlled by the owner.

Real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

A set of basic values

Java
@Entity
public class Post {
    @Id @GeneratedValue
    private Long id;
    private String title;

    @ElementCollection
    @CollectionTable(name = "post_tags", joinColumns = @JoinColumn(name = "post_id"))
    @Column(name = "tag")
    private Set<String> tags = new HashSet<>();
}

Hibernate creates post_tags(post_id, tag). There is no primary key of its own; for a Set the pair (post_id, tag) is the key. The collection table rows exist only while the post exists: deleting the post deletes its tags, and removing a tag from the set deletes that row.

Lists and order

Java
@ElementCollection
@OrderColumn(name = "position")
private List<String> steps = new ArrayList<>();

A plain List without @OrderColumn is a bag: it has no key, so Hibernate cannot update a single row and may delete all rows of the collection and re-inserts them after any change. @OrderColumn stores the index, giving each row an identity, but inserting at the front still renumbers rows. If order is not important, prefer a Set.

Maps

Java
@ElementCollection
@CollectionTable(name = "post_settings", joinColumns = @JoinColumn(name = "post_id"))
@MapKeyColumn(name = "setting_key")
@Column(name = "setting_value")
private Map<String, String> settings = new HashMap<>();

The table post_settings(post_id, setting_key, setting_value) has the pair (post_id, setting_key) as its key.

Collections of embeddables

Values can be embeddables too (see embeddables):

Java
@Embeddable
public class PhoneNumber {
    private String type;
    private String number;
}

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

Fetching

Element collections are lazy by default, so reading post.getTags() after the session closed throws LazyInitializationException. Load them inside the session, or with a join fetch query (HQL joins). Fetching several collections of one entity at once with joins can produce a huge cartesian product, a good reason to keep each collection small.

When to use an entity instead

Use an element collection when the items are tiny, owned, never queried on their own and never shared. Use a real entity and an association (one-to-many) when items need their own id, are looked up independently, are large in number, or are referenced from elsewhere.

Stand-in: the collection table

Java Stand-in: collection table and key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: bag versus indexed list

Java Stand-in: delete-and-reinsert cost of a bag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is an @ElementCollection stored in?

    Hibernate creates a collection table with a foreign key to the owner.
  2. 2. Why is a List without @OrderColumn inefficient to update?

    Without a key or index, individual rows cannot be addressed.
  3. 3. When is an element collection a poor choice?

    Large, shared or independently queried items belong in an entity with an association.
  4. 4. What happens when you read a lazy element collection after the session is closed?

    Lazy collections need an open session or an explicit fetch.

Summary

  • @ElementCollection maps owned collections of basic values or embeddables into a collection table.
  • Prefer Set or a List with @OrderColumn; a plain List is a bag with costly updates.
  • Maps use @MapKeyColumn and @Column for key and value.
  • Collections are lazy: fetch them inside the session.
  • Items with their own identity should be entities, which is the next chapter.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: Many-to-One and One-to-Many