Hibernate first-level cache issue while encrypting and decrypting an entity property


#1

Hi,

While using Hibernate ORM 5.x (with PostgreSQL DB) in one of our projects, we are facing a strange issue.

Data is added to a table in encrypted form and decrypted during extraction. Now when we try to add a new record with encrypted data in this table, the first row is also getting automatically updated and that too with the decrypted value which was being held in the L1 cache.

So any operation that was supposed to happen on the first record, fails since the value has changed from an encrypted one to decrypted one now,

What could possibly be going wrong here? Is there any way we can ensure that the previous row which had the decrypted value in L1 cache, does not get updated again in the database while inserting a new record?

Kindly suggest,
Aditya


#2

You should not decrypt in the @Entity but in a DTO: every time you change the value of a @Entity’s field, the entity instance is flagged as dirty and the change will be flushed at sync time.

As an alternative you could put the decrypted value in a transient field.


#3

Thank you for your reply.

Is there any other alternative other than putting decrypted value in a transient field, or is this the only alternative we have as such? Is there someway we can control this via stored procedure or something like this?

Regards,
Aditya


#4

You can also play with @PrePersist and @PreUpdate to be sure the field is always in the correct format, but changing the value of a field marks the entity instance as dirty and may trigger update code (DB round trip) when not needed.


#5

@Aditya you can take a look at Jasypt: https://github.com/grelland/jasypt-hibernate5

It’s what we used a long time ago to deal with automatic encryption with Hibernate.


#6

Hi,

Is it possible to encrypt/decrypt only certain fields in a particular table in hibernate? If yes, what are the different ways we can do it? Is there a DB agnostic solution for this?

-Aditya


#7

Is it possible to encrypt/decrypt only certain fields in a particular table in hibernate?

Yes, it is. Check out this article for more details.

If yes, what are the different ways we can do it? Is there a DB agnostic solution for this?

Yes, it is. Use database-specific XML mapping files as explained in this article. At project built time, the Maven profile should pick up the right XML mapping file so you can customize the database-specific @ColumnTransformer for each supported database.