可以使用 JPA Converter 实现这一点。
实体;
@Id
@GeneratedValue
Long id;
@Column(name = "mapvalue")
@Convert(converter = MapToStringConverter.class)
Map<String, String> mapValue;
转换器:
@Converter
public class MapToStringConverter implements AttributeConverter<Map<String, String>, String> {
ObjectMapper mapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(Map<String, String> data) {
String value = "";
try {
value = mapper.writeValueAsString(data);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return value;
}
@Override
public Map<String, String> convertToEntityAttribute(String data) {
Map<String, String> mapValue = new HashMap<String, String>();
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
};
try {
mapValue = mapper.readValue(data, typeRef);
} catch (IOException e) {
e.printStackTrace();
}
return mapValue;
}
}
保存数据:
Map<String, String> mapValue = new HashMap<String, String>();
mapValue.put("1", "one");
mapValue.put("2", "two");
DataEntity entity = new DataEntity();
entity.setMapValue(mapValue);
repo.save(entity);
该值将存储在数据库中
{"1":"three","2":"two"}