I have a Sprint Boot web service that is using JPA to map to an underlying SQL database.
One of the domain classes has a property that is a complex Java object that I do not want to persist with the normal mapped/joined tables. Instead I want to map this Java object to a single column in the main table, and ideally store the data in a JSON format in a string column.
Any suggestions?
You can use jpa's AttributeConverter :
@Converter
public class MyObjectConverter implements AttributeConverter<MyObject, String> {
@Override
public String convertToDatabaseColumn(MyObject myObject) {
//convert myobject to json: for instance use ObjectMapper from Jackson
if( myObject == null )
return null;
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(myObject );
}
@Override
public MyObject convertToEntityAttribute(String myObjectString) {
// convert myObjectString back to object
if( myObjectString== null )
return null;
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(myObjectString, MyObject.class);
}
}
and use it in your entity as..
@Column
@Converter(converter = MyObjectConverter.class)
MyObject myObject;
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.