Enabling Second-Level Cache

JPA specification supports a second-level cache which is managed on EntityManagerFactory level. That means entities can be cached in the second-level which can live across multiple EntityManager sessions. This helps improve performance by avoiding expensive database calls, keeping the entity data local to the application. A second-level cache is typically transparent to the application, as it is managed by the persistence provider.

Second-level cache is optional for the JPA Provider

Support for a second-level cache is not required by the Java Persistence API specification, setting the second-level cache mode in persistence.xml will have no effect if we use a persistence provider that does not implement a second-level cache. In the following example, we will use Hibernate as the JPA provider which supports second-level cache.

Enabling Second-Level cache

To enable second-level cache we have to use <shared-cache-mode> element in the persistence.xml, with one of the values as defined in SharedCacheMode enum.

In following example we will use shared-cache-mode=ALL which causes all entities and entity-related state and data to be cached.

As seen above Hibernate did not use any 'select' statement to load Employee entity when we used find() method, that because the entity was cached at the time of 'insert' stage (when persist() was called).