How to map a map JSON column to Java Object with JPA

前端 未结 6 1043
一整个雨季
一整个雨季 2020-12-02 14:22

We have a big table with a lot of columns. After we moved to MySQL Cluster, the table cannot be created because of:

ERROR 1118 (42000): Row size too l

6条回答
  •  孤街浪徒
    2020-12-02 15:19

    You can use a JPA converter to map your Entity to the database. Just add an annotation similar to this one to your params field:

    @Convert(converter = JpaConverterJson.class)
    

    and then create the class in a similar way (this converts a generic Object, you may want to specialize it):

    @Converter(autoApply = true)
    public class JpaConverterJson implements AttributeConverter {
    
      private final static ObjectMapper objectMapper = new ObjectMapper();
    
      @Override
      public String convertToDatabaseColumn(Object meta) {
        try {
          return objectMapper.writeValueAsString(meta);
        } catch (JsonProcessingException ex) {
          return null;
          // or throw an error
        }
      }
    
      @Override
      public Object convertToEntityAttribute(String dbData) {
        try {
          return objectMapper.readValue(dbData, Object.class);
        } catch (IOException ex) {
          // logger.error("Unexpected IOEx decoding json from database: " + dbData);
          return null;
        }
      }
    
    }
    

    That's it: you can use this class to serialize any object to json in the table.

提交回复
热议问题