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.
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.