Search code examples
jpacaching

Changes in Database not reflected in JPA Entity


I have a configuration table that I load at the beginning of the application. If I change any value on the database table, it is not reflected on the app and it is doing the query again.

    @Stateless()
@LocalBean()
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class DatosConfiguracionDAO {
    private static final Logger log = Logger.getLogger(DatosConfiguracionDAO.class);
    @PersistenceContext(unitName = Constantes.Conexiones.UNIT_PLACSP)
    private EntityManager em;
    
    
    public List<ConfiguracionEntity> findAllConfiguracion() throws GeacoPlacspException {
        try {
            
            TypedQuery<ConfiguracionEntity> query = em.createNamedQuery("ConfiguracionEntity.findAll",
                    ConfiguracionEntity.class);
            return query.getResultList();
        }catch(Exception e) {
            log.error("findAllConfiguracion" + e);
            throw new GeacoPlacspException(ErrorType.ERROR104,e.getMessage());
        }
    }

}

Entity

   @Entity
        @Table(name=NOMBRE_TABLA_CONFIGURACION)
        @NamedQuery(name="ConfiguracionEntity.findAll", query="SELECT c FROM ConfiguracionEntity c")
        public class ConfiguracionEntity extends BaseEntity implements Serializable {
}

I'm using weblogic 12, and restart the weblogic is the only way to update the values in the app


Solution

  • 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.