目前我可以用
AttributesConverter
. 很好
Spring
可以自动将Jackson映射器注入其中:
@Entity
public class Customer {
@Convert(converter = AddressConverter.class)
@Lob
@Column(columnDefinition = "text")
private List<Address> address;
}
@Converter
public class AddressConverter implements AttributeConverter<List<Address>, String> {
private ObjectMapper objectMapper;
@Autowired //injected by spring
public AddressConverter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public String convertToDatabaseColumn(List<AddressConverter> list) {
try {
if (!CollectionUtils.isEmpty(list))
return objectMapper.writeValueAsString(list);
} catch (final JsonProcessingException e) {
LOGGER.error(e);
}
return null;
}
@Override
public List<Address> convertToEntityAttribute(String json) {
try {
if (StringUtils.isNotBlank(json))
return objectMapper.readValue(json, List.class);
} catch (final IOException e) {
LOGGER.error(e);
}
return null;
}
}