Cmobilecom JPA 2.2.2 Developer Guide

18 Cache

To enable 2nd-level cache for improving performance, specify shared-cache-mode in META-INF/persistence.xml. e.g.,
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
or specify property javax.persistence.sharedCache.mode when creating an EntityManagerFactory. e.g.,
    Map<String, Object> properties = new HashMap<>();
    properties.put(Constants.SHARED_CACHE_MODE, SharedCacheMode.ENABLE_SELECTIVE);
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu_name", properties);
For example,
@Entity
public class Employer {

}

@Cacheable(true)
@Entity
public class Employee {

}

@Entity
public class FullTimeEmployee extends Employee {
    
}

@Cacheable(false)
public class Department {

}
Shared cache mode: @Cacheable annotation or its corresponding XML is inheritable by subclasses. If an entity class is cacheable, then its subclasses are cacheable if not overridden.

Caching is transparent to applications, but its behavior can be controlled by the properties: javax.persistence.cache.retrieveMode and javax.persistence.cache.storeMode for cache retrieve and store modes respectively. For example, retrieve an Employee entity from persistence bypassing cache, refresh the entity in the cache, then make changes to the entity, and finally commit the transaction and update the cache with the committed entity.
    EntityManager em = ... // get an EntityManager
    
    Map<String, Object> properties = new HashMap<>();
    properties.put(Constants.CACHE_RETRIEVE_MODE, CacheRetrieveMode.BYPASS);
    properties.put(Constants.CACHE_STORE_MODE, CacheStoreMode.REFRESH);
    Employee employee = em.find(Employee.class, "123001", properties);
    
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    
    employee.setName("New Name");
    
    transaction.commit();
Persistence ContextLockFrames / No Frames