Zhirayr Zhirayr - 9 months ago 44
Java Question

Java entity manager does not load changes when I manually update row

I have a simple service injected by guice. It uses Hibernate, EntityManager.

class BrillantPaulaServiceImpl implements BrillantPaulaService {
EntityManager em;

public Status EnqueueStatusCheck(Integer statusId) {
Status status = em.find(Status.class, statusId);
EntityTransaction transaction = em.getTransaction();
try {
//..... do some work
} finally {
if (transaction.isActive()) {
return status;

When I manually update row from pgsql, the "Status status = em.find(Status.class, statusId);" does not view changes. It returns old entity. What is the possible issue?

Answer Source

What em.find(...) does is that it first checks persistence context and because there is cached entity it returns it instead of getting it from database. Here is some quote from here:

Find by primary key, using the specified properties. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there. If a vendor-specific property or hint is not recognized, it is silently ignored.

In the case that cache is used, JPA will get the entities from there. It will track changes to those entities only if they are modified via JPA. If you update the underlying data yourself, either directly or via some other external system, JPA will not be aware of those changes.