JPA/Hibernate: store EnumSets

33 views Asked by At

I have a @Entity that stores in a DB (MariaDB) - JPA/Hibernate with Spring-Boot.

@Entity
public class MyFile
{
    public static enum Type { DIR, FILE, SYS };
    
    public static enum Rights { R, W, X };
    
    
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long id;
    
    @NotNull
    @Column (unique = false)
    private String name;
    
    @NotNull
    @Column (unique = false)
    @Enumerated (EnumType.STRING)
    private Type t;

    @NotNull
    @Column (unique = false)
    ???
    private EnumSet <Right> rights;
    
    ....

I added a EnumSet for rights (like a bitmask).

I am not sure how to annotate for JPA for the EnumSet. Found articles for simple enums (like Type) but not for EnumSets.

I also do not want to wirte converters - it should work out of the box if possible.

1

There are 1 answers

0
Ahmed Nabil On

EnumSet is a Collection and should be treated like one.

@ElementCollection
@CollectionTable(name = "rights", joinColumns = @JoinColumn(name = "myfile_id"))
@Enumerated(EnumType.STRING)
private Set<Right> rights;

IMPORTANT: Program to the interface Set and use the implementation EnumSet in setter and constructor.

private **Set**<Right> rights;

public void setRights(**EnumSet**<Right> rights) {
    this.rights = rights;
}