Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Collection of Enum types that implement interface

I've got a tricky thing I'm trying to map with Enums for storing static data.

It starts off with enum classes declared as such:

interface MyInterface {
    String getName();
}

public enum A implements MyInterface {
FIRST_A("First A");
private final String name;
private A(String name) {
this.name = name;
}
public String getName() {
return name;
}

public String toString() {
return name;
}
}

public enum B implements MyInterface {
FIRST_B("First B");
private final String name;
private B(String name) {
this.name = name;
}
public String getName() {
return name;
}

public String toString() {
return name;
}
}

Now I want to use these as:

List<MyInterface> elements

The problem comes in mapping the collection. I can persist these just fine normally if I use a CompositeUserType I've written for writing the class of the enum being persisted as well as the String value that would come from persisting an @Enumerated with the EnumType.STRING. In those cases I can declare:


@Type(type="MyCustomEnumType.class")
@Columns(columns = {
            @Column(name = "enumValue"), @Column(name = "enumClass")
})
private Enum enumValue;

In that case I can persist them just fine, but I'm uncertain if using @Type on the collection will make all items inside that collection persist using that custom type. Should I use @ElementCollection as well on it since it's such that it's embeddable? Or do I use the user type class I've written as the targetClass of the collection? I'm a bit confused on how it works for something like that. I want to keep it generic enough to persist A or B possibly in the collection (although it will end up being only one type per entity persisted, but could be either).

I'd prefer not to have to set this up as an Entity class due to it being static data that won't change, but may have a new version in the future which would end up being another enum.

like image 723
kjordan Avatar asked Nov 14 '22 00:11

kjordan


1 Answers

Hibernate doesn't support that out of the box but you can write your own usertype to store the fully qualified Enum name, for example com.package.Type.ENUM_VALUE. I don't know if user types can be used to map one value/object to more than one database column.

There's an example here of a usertype to store an enum. The example just stores an enum, but you might be able to use it as a template.

like image 76
Augusto Avatar answered Jan 06 '23 10:01

Augusto