Leon Borko
Leon Borko

Reputation: 198

How to mark entites as cacheable

I have java jar library with JPA entities, spring repositories and spring services and now i included this library in project where i want some entities to be cacheable (cached in second level cache) and don't want to change library.

Is is possible to configure Cachemanager to include entities which are not market as @Cacheable?

Upvotes: 1

Views: 2158

Answers (2)

stakahop
stakahop

Reputation: 951

If you want to use Hibernate's session-independent second level cache which can be used by multiple Hibernate Session you must first activate it.

First modify persistence.xml, so add:

<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>

and property:

<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>

You can choose between ALL to cache all entities, NONE to don't cache any entities, ENABLE SELECTIVE to select the entities that will be cached and DISABLE SELECTIVE to select the entities that will not be cached. Prefer ENABLE SELECTIVE because it requires you to explicitly decide which entities are cached.

Annotate your entity with JPA @Cacheable or Hibernate @Cache annotation.

You can also use the @Cacheable (false) annotation to exclude an entity from caching if you use shared cache mode DISABLE SELECTIVE.

Hibernate doesn't use the second-level cache with JPQL or criteria queries.

If you want to use query caching modify persistence.xml, so add properties:

<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>

and activate caching for query with setCacheable(boolean b); method, (eg.) :

Session s = (Session) em.getDelegate(); 
Query q = s.createQuery("SELECT b FROM Book b WHERE id = :id"); 
q.setParameter("id", 1L); 
q.setCacheable(true); 
Book b = q.uniqueResult();

Hibernate now stores the result of this query in the query cache. When your next use case executes this query, Hibernate checks if the query cache contains a result for the given parameter values. If the cache contains a matching record, Hibernate gets the query result from there. Otherwise, it executes the query and store its result in the cache.

Upvotes: 1

Smutje
Smutje

Reputation: 18123

If you have control over the persistence.xml, you can add

<shared-cache-mode>ALL</shared-cache-mode>

for a persistence unit to cache alle entities or

<shared-cache-mode>DISABLE_SELECTIVE</shared-cache-mode>

to enable caching for all entities but the ones you marked as @Cacheable(false) (see also https://docs.oracle.com/javaee/7/api/javax/persistence/SharedCacheMode.html)

Upvotes: 2

Related Questions