How to use JPA2’s @Cacheable instead of Hibernate’s @Cache

According to the JPA 2.0 specification, if you want to selectively cache entities using the @Cacheable annotation, you’re supposed to specify a <shared-cache-mode> in the persistence.xml (or the equivalent javax.persistence.sharedCache.mode when creating the EntityManagerFactory).

Below, a sample persistence.xml with the relevant element and properties:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
  <persistence-unit name="FooPu" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    ...
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
      ...
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.SingletonEhCacheProvider"/>
      <property name="hibernate.cache.use_second_level_cache" value="true"/>
      <property name="hibernate.cache.use_query_cache" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

Note that I’ve seen at least one issue HHH-5303 related to caching. So the above is not guaranteed 🙂

References

  • Hibernate EntityManager reference guide
  • JPA 2.0 Specification
    • Section 3.7.1 “The shared-cache-mode Element”
    • Section 11.1.7 “Cacheable Annotation”

Leave a Comment