2

Effective Java, Item 32, states Use EnumSet instead of bit fields. I also found this nice tutorial on the topic. This book has been around for a while, so why don't I find any posts on how to persist an EnumSet with Hibernate? Well, I actually found this one, and another one, but they are both quite old, point to the same and much older solution, which unfortunately did not help me, perhaps because of my lack of deeper hibernate knowledge? Here is an abstract of my code:

public class MyThing {
    public enum MyOptions {
        FLAG1, FLAG2
    }

    @Id
    private Long id;

    @Column(name = "options")
    private EnumSet<MyOptions> options;

    // [other fields, getters, setters etc]
}

I've tried other annotations like

@ElementCollection

with and without (targetClass = MyOptions.class)

and

@JoinTable(name = "my_options",
    joinColumns = @JoinColumn(name = "id"))

and also

@OneToMany
@JoinColumn(name = "options")

but with no luck.

Preferably, I'd store the information in a new column of the my_thing table, but I could also live with a separate table for the enums, if required.

aweibell
  • 405
  • 1
  • 5
  • 14

1 Answers1

4

Try this

@ElementCollection
@CollectionTable(name = "my_options", 
        joinColumns = @JoinColumn( name = "mything_id"))
@Column(name = "option")
@Enumerated(EnumType.STRING)
private Set<MyOptions> options;

With this configuration, you need a database table named my_options with columns option and mything_id which targets MyThing table.

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • 1
    I would like to add that when I declare `@Enumerated(EnumType.STRING) private EnumSet regions;` I get `org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements:` so I had to modify my getter to get an instance of EnumSet safely by doing this: `public EnumSet getRegions() {` ` return EnumSet.copyOf(regions);` ` }` – Pacu Dec 13 '15 at 03:23