JPA Attribute Converters
zhangzhenhuajack opened this issue · 0 comments
zhangzhenhuajack commented
比如一个数据是 1 ,数据库里面通过加密保存的是aaa,我现在查询的时候触发了convertToEntityAttribute 解密成了 1,我现在需要更改一下加密方式,把他改成bbb,我想在convertToDatabaseColumn修改一下,如果是1 保存的时候映射到bbb。但是现在查出来已经是1了,但是保存的时候因为没有变更或者是别的什么原因,没有触发convertToDatabaseColumn。有的表通过更新version或者update time就可以触发,但是有一张表在设计的时候没有这些
see: https://www.baeldung.com/jpa-attribute-converters
@Entity(name = "PersonTable")
public class Person {
@Convert(converter = PersonNameConverter.class)
private PersonName personName;
// ...
}
@Converter
public class PersonNameConverter implements
AttributeConverter<PersonName, String> {
private static final String SEPARATOR = ", ";
@Override
public String convertToDatabaseColumn(PersonName personName) {
if (personName == null) {
return null;
}
StringBuilder sb = new StringBuilder();
if (personName.getSurname() != null && !personName.getSurname()
.isEmpty()) {
sb.append(personName.getSurname());
sb.append(SEPARATOR);
}
if (personName.getName() != null
&& !personName.getName().isEmpty()) {
sb.append(personName.getName());
}
return sb.toString();
}
@Override
public PersonName convertToEntityAttribute(String dbPersonName) {
if (dbPersonName == null || dbPersonName.isEmpty()) {
return null;
}
String[] pieces = dbPersonName.split(SEPARATOR);
if (pieces == null || pieces.length == 0) {
return null;
}
PersonName personName = new PersonName();
String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null;
if (dbPersonName.contains(SEPARATOR)) {
personName.setSurname(firstPiece);
if (pieces.length >= 2 && pieces[1] != null
&& !pieces[1].isEmpty()) {
personName.setName(pieces[1]);
}
} else {
personName.setName(firstPiece);
}
return personName;
}
}