Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JPA Attribute Converters #47

Open
zhangzhenhuajack opened this issue Jun 17, 2022 · 0 comments
Open

JPA Attribute Converters #47

zhangzhenhuajack opened this issue Jun 17, 2022 · 0 comments

Comments

@zhangzhenhuajack
Copy link
Owner

比如一个数据是 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;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant