The underlying problem here is the 1st level cache of JPA. From the JPA spec Version 2.2 section 3.1. emphasise is mine:
An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.
This is important because JPA tracks changes to that entity in order to flush them to the database. As a side effect it also means within a single persistence context an entity gets only loaded once. This why reloading the changed entity doesn't have any effect.
You have a couple of options how to handle this:
Evict the entity from the EntityManager
.
This may be done by calling EntityManager.detach
, annotating the updating method with @Modifying(clearAutomatically = true)
which evicts all entities.
Make sure changes to these entities get flushed first or you might end up loosing changes.
Use a different persistence context to load the entity.
The easiest way to do this is to do it in a separate transaction.
With Spring this can be done by having separate methods annotated with @Transactional
on beans called from a bean not annotated with @Transactional
.
Another way is to use a TransactionTemplate
which works especially nicely in tests where it makes transaction boundaries very visible.