Reputation: 427
Hibernate provided the way to insert a record into database via the save() method. Ex: User() user = new User(int id, String name); userDAO.save(user);
which is great. However I am stuck at this: I need to execute this query to insert a record to the table user SQL query: "insert into user values("My name", AES_ENCRYPT("clear_txt", "key")); Just for example: My table user has two fields: 'name', and 'password'. The password needed to encrypt with some key. AES_ENCRYPT is a function in MySQL.
How do I do this the Hibernate way? how do you deal with a requirement to encrypt a field in database with provided key?
Upvotes: 0
Views: 1997
Reputation: 117
How do I do this the Hibernate way? how do you deal with a requirement to encrypt a field in database with provided key?
Hibernate way to work with MySQL:
// `username` varchar(255) DEFAULT NULL,
@Column(name = "username")
@ColumnTransformer(
read = "cast(aes_decrypt(username, 'yourkey') as char(255))",
write = "aes_encrypt(?, 'yourkey')")
private String username;
Hibernate will transform the for the username column into sql during get:
Hibernate: select this_.id as id1_6_4_, ..., cast(aes_decrypt(this_.kronologis, 'ABC') as char(1020)) as kronolo11_6_4_,...
during save:
Hibernate: insert into e010_k2_pusdalops.kejadian (...kronologis...) values (..., aes_encrypt(?, 'ABC'),...)
Hope that solves your problem.
Cheers.
Upvotes: 0
Reputation: 692023
You could encrypt in Java, before persisting to the database, or you could use a 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(?)"
Upvotes: 0