Hibernate disable dirty checking

634 Views Asked by At

I would like to globally disable dirty checking in my application (spring data, hibernate). My goal is that JPA generates update/insert queries only when I explicitly call myRepo.save() or myRepo.myUpdateQuery().

All my entities have final fields and unmodifyiable collections, so I really do not need dirty checking. I always handle updates explicitly.

Still, I get massive performance problems because JPA generates redundant update queries every time a field gets lazy-loaded.

Solutions I have seen so far (no success):

  • Use FlushMode=MANUAL. This is an overkill since I will have to make sure flush() gets called manually. Huge refactoring I cannot afford.

  • Use readonly transactions. This would also block my explicit save/modifying query calls. I want those to keep working.

  • Detach the entities. This will has extra side effects such as not being able to perform further lazy-loads, which is a nogo. Also, it will require huge refactoring. For the most part, I do not even have access to EntityManager since I am using spring data repositories.

  • Use Stateless Sessions. Not an option since things like Lazy Loading will also get disabled.

1

There are 1 best solutions below

0
On

Use FlushMode=MANUAL. This is an overkill since I will have to make sure flush() gets called manually. Huge refactoring I cannot afford.

If you don't want to do that, there is not much you can do if you also need lazy loading. Maybe you can load entities as read only (see org.hibernate.Session#setReadOnly and org.hibernate.Session#setDefaultReadOnly) and upgrade them to become mutable, but that will again require calling explicit methods just like calling flush explicitly.

I can tell you from past projects though, that it is well worth the refactoring to ensure no lazy loading happens outside of the service layer.

Maybe a DTO approach like Blaze-Persistence Entity-Views is what you are looking for? It's read only by default, but you can convert your read only data to updatable types on demand to model your write concerns.