简体   繁体   中英

Spring Boot JPA: Storing entity as JSON

In my Spring Boot app I have Entity like that:

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

  @Id
  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.

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

public class DataJsonConverter implements AttributeConverter<Data, String> {

    private ObjectMapper objectMapper = ...;

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

    @Override
    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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM