Overriding array(list) type conversions in Spring Data R2DBC

Viewed 1738

I'm using Postgres as my datasource and I've created a custom Spring converter for a property that holds a list of my custom objects:

@Slf4j
@WritingConverter
@AllArgsConstructor
public class CustomObjectListToStringConverter implements Converter<List<CustomObject>, String> {

    @Override
    public String convert(@Nonnull List<CustomObject> source) {
        try {
            return objectMapper.writeValueAsString(source);
        } catch (JsonProcessingException e) {
            log.error("Error occurred while serializing list of CustomObject to JSON.", e);
        }
        return "[]";
    }

}

Conversion goes smoothly but IllegalArgumentException is raised in getArrayType method of PostgresArrayColumns class because my custom type is not a simple type.

Is there a way to circumvent this guard for some property?

2 Answers

It is not supported intentionally based on the documentation.

Please note that converters get applied on singular properties. Collection properties (e.g. Collection) are iterated and converted element-wise. Collection converters (e.g. Converter<List>, OutboundRow) are not supported.

Source: spring-data-r2dbc mapping reference

Solution:
Create a wrapper class (complex type) as follows:

class CustomObjectList { 
  List<CustomObject> customObjects;
}

Then, you apply a converter Converter<CustomObjectList, String> and vice versa.

public class CustomObjectListToStringConverter implements Converter<CustomObjectList, String> {
Related