🔸 TLDR
Hibernate's @ColumnTransformer can transform a column automatically when reading and writing it.
With PostgreSQL + pgcrypto:
▪️ Java writes plain text
▪️ PostgreSQL encrypts it
▪️ The database stores encrypted bytes
▪️ Hibernate decrypts it automatically when reading
Example:
So your application can simply do:
But PostgreSQL stores something looking like:
Then:
returns:
🔸 HOW DOES IT WORK?
Hibernate applies the write expression when generating SQL for INSERT/UPDATE:
And the read expression when selecting the column:
Your domain model therefore doesn't need explicit:
logic everywhere. ✅
🔸 POSTGRESQL SIDE
Enable pgcrypto:
This gives you functions such as:
🔸 ⚠️ DON'T HARDCODE THE KEY
Putting this inside your mapping would be a terrible idea:
The original example uses a PostgreSQL setting accessed through:
But even storing the secret in postgresql.conf should NOT be considered a production-grade key-management strategy.
Production systems should normally rely on proper secrets/key management and appropriate rotation/access controls. 🔑
🔸 TAKEAWAYS
▪️ @ColumnTransformer transforms SQL reads and writes transparently
▪️ Encryption can stay outside your Java business logic
▪️ PostgreSQL pgcrypto can encrypt sensitive columns
▪️ Your entity sees plaintext while the database stores ciphertext
▪️ Encryption key management is just as important as encryption itself
▪️ JPA portability is useful, but Hibernate-specific features can solve very real problems elegantly
Sometimes using your JPA provider's native capabilities is much cleaner than rebuilding everything yourself. 🚀
#java #hibernate #jpa #postgresql #security #encryption #javadeveloper #database #softwareengineering #backenddevelopment #javaprogramming
https://vladmihalcea.com/how-to-encrypt-and-decrypt-data-with-hibernate/
Go further with Java certification:
Java👇
https://bit.ly/javaOCP
Spring👇
https://bit.ly/2v7222
SpringBook👇
https://bit.ly/springtify
JavaFullstackBook👇
https://bit.ly/jfstack27