Anmol Gupta
Anmol Gupta

Reputation: 2957

Is this a right approach to use Enum to persist it in database?

So, I have a class(an entity) which has OneToMany relationship with an enum (another entity)

@Entity
class MyClass {
    @Id
    int id;

    @OneToMany
    List<MyEnumWrapper> myEnum;
}

public enum MyEnum {
    VALUE1,
    VALUE2
    ;
}

@Entity
public class MyEnumWrapper {
    @Id
    private String value;

    public MyEnumWrapper(MyEnum value){
           this.value = value
    }

    public MyEnum getValue {
           return MyEnum.valueOf(value);
    }
}

Does wrapping the enum just to make a different table for it in the database makes sense ?

EDIT: I get the problems with this design. But, my requirement is to have a separate table for the enum as it will get associated with many entities. So, is there a standard way to make table of just an Enum ?

Upvotes: 0

Views: 91

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

No, it doesn't make much sense. First because the association is probably not a OneToMany, but a ManyToMany: a given enum is probably contained in several instances of MyClass.

Second because, if that's really what you want, why would you use a String as the ID of the enum wrapper rather than using the enum itself?

Finally, unless you really want a table containing only the enum instances, you could simply use an element collection:

@Entity
class MyClass {
    @Id
    int id;

    @ElementCollection
    Set<MyEnum> myEnums = new HashSet<>();
}

Upvotes: 1

Related Questions