Search code examples
javapersistencejpa-2.0eclipselinkejb-3.0

when and why the EclipseLink Caching is used?


in our development team I noticed two ways to use EntityManager :

1. first way

public class ReferentielDaoImpl implements ReferentielDaoLocal {
      @PersistenceContext(unitName = "ErpCCF-ejbPU")
       private EntityManager em;
public List<Alerte> findAll(){
    try {
                em.getEntityManagerFactory().getCache().evictAll();
                String req = "SELECT a FROM Alerte a ORDER BY a.idAlerte DESC";
                List<Alerte> alertes = em.createQuery(req).getResultList();
                return alertes;
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
            return null;
}
}

2.second way

public class ReferentielDaoImpl implements ReferentielDaoLocal {
          @PersistenceContext(unitName = "ErpCCF-ejbPU")
           private EntityManager em;
    public List<Alerte> findAll(){
        try {
                    String req = "SELECT a FROM Alerte a ORDER BY a.idAlerte DESC";
                    List<Alerte> alertes = em.createQuery(req).getResultList();
                    return alertes;
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                }
                return null;
    }
    }

What is the difference between these two methods?

What the correct method?


Solution

  • EntityManagerFactory#getCache() returns the second level cache, i.e. a cache that is common for all EntityManager instances. EclipseLink automatically uses a shared object cache, so that if multiple EntityManager query the same object, the database does not have to be contacted more than once.

    Usually, the only reason why you might have to evict (=clear) the second level cache is if you have modified the database directly (e.g. using direct JDBC calls or any other process that does not use your JPA persistence unit). If that's not the case, don't evict the cache - this will render it useless and slows down your application.

    For more information, see http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching