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

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<Object, String> {

  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.

Leave a Comment