Hibernate Annotations – Collection of Enums

 In Development, Technical

Using a CoffeeRoster to demonstrate an example of how to store a collection of enums with Hibernate Annotations and @CollectionOfElements.

Coffee Roster Example

One of the items that I’ve struggled to find documentation on is how to store a collection of enums with Hibernate Annotations.

Lets say for this example that we want to have an object called CoffeeRoster. The purpose of this object is to record what days a person will be responsible for buying coffee and snacky things for the office. And in this object we will store the person’s name and a set of days.

@Entity
public class CoffeeRoster{
   @Id @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   @CollectionOfElements
   @Enumerated(EnumType.STRING)
   private Set buyingDays = new HashSet();

   private String name;

   //default no args constructor, getters and setters.
}

Taking a look at that example, we have an annotation for the fact that this is an entity and we note that we have a generated value id field.

At the bottom you’ll see that ‘name’ doesn’t have an annotation. This is because if you don’t explicitly declare an annotation, Hibernate will try to store it by itself. If we didn’t want name to be stored in the database, we’d have to use the @Transient annotation to declare it as transient.

So on to the important bit about the collections…

@CollectionOfElements

The correct way to store a collection is to use this annotation. In the background, a table is created for us that will be called CoffeeRoster_buyingDays which will have two columns, CoffeeRoster_id and element.

Then you’ll notice the @Enumerated(EnumType.STRING). If you try this example without this line, the ordinal of the enum is stored in the database, but if you use this annotation, the name of the enum is used instead.

In our database we can now see the following:

CoffeeRoster_id element
3 MONDAY
3 WEDNESDAY
3 FRIDAY

Start typing and press Enter to search