Hibernate JPA @ColumnTransformer Example
@ColumnTransformer
The @ColumnTransformer annotation is used to customize how a given column value is read from or written into the database.ColumnTransformer
Custom SQL expression used to read the value from and write a value to a column. Use for direct object loading/saving as well as queries. The write expression must contain exactly one '?' placeholder for the value. For example: read="decrypt(credit_card_num)" write="encrypt(?)"
@ColumnTransformer example
@Entity(name = "Employee")
public static class Employee {
@Id
private Long id;
@NaturalId
private String username;
@Column(name = "pswd")
@ColumnTransformer(
read = "decrypt( 'AES', '00', pswd )",
write = "encrypt('AES', '00', ?)"
)
private String password;
private int accessLevel;
@ManyToOne(fetch = FetchType.LAZY)
private Department department;
@ManyToMany(mappedBy = "employees")
private List<Project> projects = new ArrayList<>();
//Getters and setters omitted for brevity
}
If a property uses more than one column, you must use the forColumn attribute to specify which column the @ColumnTransformer read and write expressions are targeting.
Example : @ColumnTransformer forColumn attribute usage
@Entity(name = "Savings")
public static class Savings {
@Id
private Long id;
@Embedded
@ColumnTransformer(
forColumn = "money",
read = "money / 100",
write = "? * 100"
)
private MonetaryAmount wallet;
//Getters and setters omitted for brevity
}
Comments
Post a Comment