Home > Mobile >  Spring Boot JPA: How to change the way an attribute is saved
Spring Boot JPA: How to change the way an attribute is saved

Time:01-23

I need to find a way to insert an entity with attributes using JPA. One of the attribute is representing a hexstring. Because of the used DB and other requirements I am forced to insert this string with the syntax X'stringValue' into the DB.

Unfortunately I didn't find any way to insert this syntax. I tried it with @Query (native sql) and @Columntransformer(X'?'), but nothing helps, because the questionmark is always used as a string because of the single quotes.

I would need something like: Hibernate: insert into table (SPECIAL_COLUMN, NORMAL_COLUMN) values (X'?', ?)

CodePudding user response:

Implement an AttributeConverter. Before an attribute is saved to DB, its value will be computed using convertToDatabaseColumn(). When you read this attribute from DB, the value in the DB will be converted using convertToEntityAttribute() and then set to the attribute.

Briefly, it can look as follows:

public class XPrefixConverter implements AttributeConverter<String , String> {

    public String convertToDatabaseColumn(String attribute) {
        if (attribute != null) {
            return HexFormat.of().formatHex(attribute.getBytes());
        } else {
            return null;
        }
    }

    public String convertToEntityAttribute(String attribute) {
        if (attribute = null) {
            return new String(HexFormat.of().parseHex(value));
        } else {
            return null;
        }
    }

}

Then use it for specific attribute:

@Convert( converter = XPrefixConverter.class )
private String hexString;

  • Related