Site icon akquinet AG – Blog

JPA Pitfalls (9): UPDATE/DELETE and Persistence Context

This blog article is part of a “series of blog articles” about common pitfalls using JPA and ways to avoid them. In this article, we describe bulk the effect of JPQL operations on the EntityManager cache.

A bulk UPDATE or DELETE JPQL query is directly executed in the database. The persistence context is not synchronized with the result of the bulk operation.

UPDATE Insurance i SET i.carrier = 'UPDATED' WHERE i = :ins

DELETE FROM Insurance i WHERE i = :ins

When running the above UPDATE or DELETE JPQL query, insurance entities in memory are not affected by the query. That means the entity in memory is not updated or not deleted. Any subsequent modification might lead to inconsistencies at flush or commit time.

Recommendation: be careful with entities in the EntityManager cache when running UPDATE or DELETE JPQL query.

You can find an example of this pitfall and its solution in the class UpdateQueryExperiment in this project:

Exit mobile version