Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map<String, String> single column mapping in spring data jdbc

I'm trying to map a Resource class which has a Map field using Data JDBC. Here is simplified entity:

public class Resource {
    @Id
    private Long id;
    private Map<String, String> props;
}

I don't want a separate table for props, just a single column of type string or may be jsonb for postgres.

I did register converters for the map type like this:

@Configuration
public class DataJdbcConfiguration extends AbstractJdbcConfiguration {

    @Override
    public JdbcCustomConversions jdbcCustomConversions() {
        return new JdbcCustomConversions(Arrays.asList(
                JsonToStringConverter.INSTANCE,
                StringToJsonConverter.INSTANCE)
        );
    }

    @ReadingConverter
    enum JsonToStringConverter implements Converter<String, Map<String, String>> {

        INSTANCE;

        @Override
        public Map<String, String> convert(String source) {
            try {
                return new ObjectMapper().readValue(source, new TypeReference<Map<String, String>>() {
                });
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    @WritingConverter
    enum StringToJsonConverter implements Converter<Map<String, String>, String> {
        INSTANCE;

        @Override
        public String convert(Map<String, String> source) {
            try {
                return new ObjectMapper().writeValueAsString(source);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return "";
        }
    }
}

Inserts are working fine but a findAll query on the repository throws org.springframework.data.mapping.MappingException: Couldn't find PersistentEntity for type class java.lang.String!

like image 418
Bahadır Yağan Avatar asked Sep 06 '26 01:09

Bahadır Yağan


1 Answers

Set, List and Map get special treatment in Spring Data JDBC. I'm kind of surprised persisting the Map via a WritingConverter actually works.

I recommend to replace the Map with a custom type which probably wraps the Map. This way any special handling of maps won't kick in.

Of course raising this as a feature request on https://jira.spring.io/browse/DATAJDBC is also always an option.

like image 137
Jens Schauder Avatar answered Sep 07 '26 15:09

Jens Schauder



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!