JPA map collection of Enums

I was able to accomplish this in this simple way:

@ElementCollection(fetch = FetchType.EAGER)
Collection<InterestsEnum> interests;

Eager loading is required in order to avoid lazy loading inizializing error as explained here.


tl;dr A short solution would be the following:

@ElementCollection(targetClass = InterestsEnum.class)
@CollectionTable
@Enumerated(EnumType.STRING)
Collection<InterestsEnum> interests;

The long answer is that with this annotations JPA will create one table that will hold the list of InterestsEnum pointing to the main class identifier (Person.class in this case).

@ElementCollections specify where JPA can find information about the Enum

@CollectionTable create the table that hold relationship from Person to InterestsEnum

@Enumerated(EnumType.STRING) tell JPA to persist the Enum as String, could be EnumType.ORDINAL


The link in Andy's answer is a great starting point for mapping collections of "non-Entity" objects in JPA 2, but isn't quite complete when it comes to mapping enums. Here is what I came up with instead.

@Entity
public class Person {
    @ElementCollection(targetClass=InterestsEnum.class)
    @Enumerated(EnumType.STRING) // Possibly optional (I'm not sure) but defaults to ORDINAL.
    @CollectionTable(name="person_interest")
    @Column(name="interest") // Column name in person_interest
    Collection<InterestsEnum> interests;
}

using Hibernate you can do

@ElementCollection(targetElement = InterestsEnum.class)
@JoinTable(name = "tblInterests", joinColumns = @JoinColumn(name = "personID"))
@Column(name = "interest", nullable = false)
@Enumerated(EnumType.STRING)
Collection<InterestsEnum> interests;