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: https://github.com/akquinet/jpapitfalls.git.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.