Close

Accessing Second-Level Cache via Cache interface

[Last Updated: Mar 10, 2018]

An object representation for the second-level cache can be obtained via following method of EntityManagerFactory:

Cache getCache();

The returned value is an instance of Cache interface which has following methods:

package javax.persistence;
  ...........
public interface Cache {
    public boolean contains(Class cls, Object primaryKey);//returns true if the specified entity is in the cache
    public void evict(Class cls, Object primaryKey);//removes the specified entity from the cache
    public void evict(Class cls);//removes all entities of the specified type from the cache
    public void evictAll();//clear the cache
    public <T> T unwrap(Class<T> cls);
}

The method unwrap() can be used to obtain the provider specified API to access/manipulate the cache, e.g. the instance of org.hibernate.cache.spi.RegionFactory can be obtained in case of Hibernate.

Example

The Entity

@Entity
public class Employee{
  @Id
  @GeneratedValue
  private long id;
  private String name;
  private String dept;
    .............
}

The main class

public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          persistEntity();
          loadEntity();
          evictFromCache();
          printCacheState();
      } finally {
          entityManagerFactory.close();
      }
  }

  public static void persistEntity() {
      Employee employee = new Employee();
      employee.setName("Dawn");
      employee.setDept("IT");
      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(employee);
      em.getTransaction().commit();
      System.out.println("Employee inserted: " + employee);
      em.close();
      printCacheState();
  }

  private static void loadEntity() {
      EntityManager em = entityManagerFactory.createEntityManager();
      Employee employee = em.find(Employee.class, 1L);
      System.out.println("Employee loaded: " + employee);
      em.close();
      printCacheState();
  }

  private static void printCacheState() {
      Cache cache = entityManagerFactory.getCache();
      boolean contains = cache.contains(Employee.class, 1L);
      System.out.printf("Cache#contains(): %s%n", contains);
  }

  private static void evictFromCache() {
      Cache cache = entityManagerFactory.getCache();
      cache.evict(Employee.class, 1L);
      System.out.println("entity evicted");
  }
}
Employee inserted: Employee{id=1, name='Dawn', dept='IT'}
Cache#contains(): true
Employee loaded: Employee{id=1, name='Dawn', dept='IT'}
Cache#contains(): true
entity evicted
Cache#contains(): false

Example Project

Dependencies and Technologies Used:

  • h2 1.4.196: H2 Database Engine.
  • hibernate-core 5.2.12.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • hibernate-ehcache 5.2.12.Final: Integration for Ehcache into Hibernate as a second-level caching service.
  • JDK 1.8
  • Maven 3.3.9

Accessing Second-level Cache Example Select All Download
  • jpa-using-cache-interface
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also