One an entity is in PersistanceContext it does not continually checks for entity's state in database (caching). In other words, it cannot see the changes made out side the PersistanceContext.
So, you need to refresh your entityManger by em.refresh()
to reload the entity's latest state from database.
Also, keep in mind that using this method for entities that are not persisted yet, removed or detached, IllegalArgumentException
will be thrown.
An alternative solution is to simply clear your cache before fetching the entity's latest status by :
em.getEntityManagerFactory().getCache().evictAll()
P.S:
I do not know why you exactly need to change the entity's state outside the PersistanceContext and see the result in the context, but it seems like code smell.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…