'Convert a list of enums and store as 'varchar[]'

Trying to figure out how to store a list of enums in a single table column.

I started with a String and it worked. I'll show only the relevant parts of the code:

import com.vladmihalcea.hibernate.type.array.ListArrayType;

...

@Entity
@TypeDefs({
    @TypeDef(
        name = "list-array",
        typeClass = ListArrayType.class
    )
})
@Table(name = "reports")
public class Reports {
...

    @Type( type = "list-array" )
    @Column(
        name = "origins",
        columnDefinition = "varchar[]",
        nullable = false
    )
    private List<String> origins;

...

The corresponding DDL of the column in PostgreSQL is defined as

origins _varchar NULL

In Liquibase script:

<column name="origins" type="varchar[]" remarks=""/>

However when I tried to store enums with the following changes to the code (I basically changed the type and the corresponding getters/setters)

private List<Origin> origins;

The enum code looks so:

public enum Origin {
 A, B, C
}

I got the error:

nested exception is org.hibernate.MappingException: Could not instantiate Type: com.vladmihalcea.hibernate.type.array.ListArrayType

I also tried it with a converter but without success:

@Column(
        name = "origins",
        columnDefinition = "varchar[]",
        nullable = false
)
@Convert(converter = OriginConverter.class)
private List<Origin> origins;

The converter code is below:

@Converter
public class OriginConverter implements AttributeConverter<List<Origin>, List<String>> {

    @Override
    public List<String> convertToDatabaseColumn(List<Origin> origins) {
        List<String> values = new ArrayList<>();
        origins.forEach(
            origin -> values.add(origin.name())
        );
        return values;
    }

    @Override
    public List<Origin> convertToEntityAttribute(List<String> origins) {
        var values= origins.stream().map(Origin::valueOf).toList();
        return values;
    }
}

The error was:

could not insert...
...
Caused by: org.postgresql.util.PSQLException: Unsupported Types value: 21,685,669

What am I missing?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source