Wednesday, June 23, 2021

Java Hibernate Second Level Cache


Using a hibernate second level cache is useful for monolith applications that have a single process accessing an RDBMS  such as PostgreSQL.

In case of multiple JVMs, the second level cache might be an issue, as each JVM has its own second level cache, and this would cause inconsistencies.

First, lets add add dependencies to the pom.xml:



<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jcache</artifactId>
<version>5.5.0.Final</version>
</dependency>



Next, configure the cache behavior in the application.properties:



spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.use_query_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE



For each entity, that should be cached, add the annotations:



@Entity
@Table
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class MyEntity {


Old method queries should add hint to enable cache usage:




CriteriaBuilder criteriaBuilder
= entityManager.getCriteriaBuilder();
CriteriaQuery<ControlElement> criteriaQuery = criteriaBuilder.createQuery(MyEntity.class);
criteriaQuery.from(MyEntity.class);
TypedQuery<MyEntity> query = entityManager.createQuery(criteriaQuery);
query.setHint("org.hibernate.cacheable", Boolean.TRUE);
List<MyEntity> result = query.getResultList();



See more details in the following blog: https://www.baeldung.com/hibernate-second-level-cache



No comments:

Post a Comment