Tomas Marik Tomas Marik - 3 years ago 336
JSON Question

Spring Boot JPA: Storing entity as JSON

In my Spring Boot app I have Entity like that:

@Table(name = "UserENT")
public class User implements Serializable {

private String id;

private Data data;

I would like to achieve that object Data will be stored in DB in json format. But it will be mapped on Data object when selecting from DB.

Thanks for any advice.

Answer Source

You can implement a javax.persistence.AttributeConverter, as in:

public class DataJsonConverter implements AttributeConverter<Data, String> {

    private ObjectMapper objectMapper = ...;

    public String convertToDatabaseColumn(Data data) {
        try {
            return objectMapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not convert to Json", e);

    public Data convertToEntityAttribute(String json) {
        try {
            return objectMapper.readValue(json, Data.class);
        } catch (IOException e) {
            throw new RuntimeException("Could not convert from Json", e);

You can then use it by annotating your field:

@Convert(converter = DataJsonConverter.class)
private Data data;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download