Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate map list of enums without jointable

I would like to map a list of enums in Hibernate in a specific way.

It should be saved as a comma seperated array of strings in a single column, without using a jointable.

Just like the following annotation saves a single enum value as a string in the database:

@Enumerated(EnumType.STRING)

I would like to use an ElementCollection-like annotation to save the enum list or set in a single column in the database of the entity holding the list of enum values.

Is this possible?

like image 490
Cloud Avatar asked Oct 20 '25 14:10

Cloud


1 Answers

No, with @ElementCollection you have to use @CollectionTable which is a separate database table used just to store your values (actually preferable in this case).

You can have a simple String mapping and a couple of util methods for converting a CSV string to list of enums and vice versa. Something like this

private String myCSVValues;
...
public List<MyEnum> getMyEnums() {
    String[] csvs = this.myCSVValues.split(",");
    List<MyEnum> myEnums = new ArrayList<MyEnum>();
    for (String s : csvs) {
        myEnums.add(MyEnum.valueOf(s));
    }
    return myEnums;
}

public void setMyEnums(List<MyEnum> myEnums) {
    this.myCSVValues = org.apache.commons.lang3.StringUtils.join(myEnums, ",");
}

Or, you can try with @Converter to map a List<MyEnum> directly to a varchar column

@Converter(autoApply = true)
public class MyEnumConverter implements AttributeConverter<List<MyEnum>, String> {

    @Override
    public String convertToDatabaseColumn(List<MyEnum> myEnums) {
        ...
    }

    @Override
    public List<MyEnum> convertToEntityAttribute(String dbData) {
        ...
    }

}
like image 177
Predrag Maric Avatar answered Oct 23 '25 03:10

Predrag Maric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!