JDBC - Is there support for array of enums on postgres? #3158
-
I have the following enum in a postgres database and the respective Java enum: CREATE TYPE modality AS ENUM (
'FOOTBALL',
'VOLLEYBALL'
); public enum Modality {
FOOTBALL,
VOLLEYBALL;
} And an entity that have an array of modalities: CREATE TABLE court (
id UUID PRIMARY KEY,
modalities modality[] NOT NULL
); @Getter
@Setter
@MappedEntity
public class Court {
@Id
private UUID id;
@MappedProperty(definition = "modality[]", type = DataType.OBJECT)
private Modality[] modalities;
} The problem happens when trying to persist this entity, I'm getting errors like this:
Removing the @MappedProperty results in another error:
Changing everything to Set instead of array gives another one:
From the Micronaut Data docs and this PR (#1501) it looks like enum is well supporter on Micronaut Data JDBC for postgres, but it is not clear if it works on array without having a custom attribute converter for every enum in the project. Is the entity configuration wrong in this example? I've tried a bunch of @MappedProperty combinations without any success as well. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Try to define a converter, see |
Beta Was this translation helpful? Give feedback.
-
A converter worked as expected, thanks! For reference, these was the changes required (and a few questions after it): Entity // ...
@MappedProperty(converter = ModalityConverter.class)
private Modality[] modalities; Enum @TypeDef(type = DataType.OBJECT)
public enum Modality {
// ... Converter @Singleton
public class ModalityConverter implements AttributeConverter<Modality[], Array> {
@Override
public Array convertToPersistedValue(Modality[] entityValue, ConversionContext context) {
JdbcConversionContext jdbcConversionContext = (JdbcConversionContext) context;
try {
return jdbcConversionContext.getConnection().createArrayOf("modality", entityValue);
} catch (SQLException e) {
throw new IllegalStateException("Failed to convert to database array", e);
}
}
@Override
public Modality[] convertToEntityValue(Array persistedValue, ConversionContext context) {
try {
String[] rawValues = (String[]) persistedValue.getArray();
return Stream.of(rawValues)
.map(Modality::valueOf)
.toArray(Modality[]::new);
} catch (SQLException e) {
throw new IllegalStateException("Failed to convert to java array", e);
}
}
} I made a version of this using The Also, if it is possible to make And the |
Beta Was this translation helpful? Give feedback.
-
The
We still need the type to know which driver method to use to see the value. You can set the type in |
Beta Was this translation helpful? Give feedback.
Try to define a converter, see
https://github.com/micronaut-projects/micronaut-data/blob/2a9d77eec4da2a7bc150a6eaefdec48cd59967fd/data-jdbc/src/test/groovy/io/micronaut/data/jdbc/postgres/PostgresEnumSpec.groovy#L117C1-L128C2