Hibernate/JPA EhCache Configuration Example

In this post, we will see Hibernate/JPA EhCache Configuration Example Using Spring Boot and Oracle. We are going to use Hibernate 5 and Spring Boot 2.x for this tutorial.

Introduction.

EhCache is used for second-level cache to reduce the number of queries in the database and for performance improvement. Hibernate provides inbuilt support for EhCache and Infinispan. Here we will see hibernate second level cache example using EhCache.

First, we will save one record in the database, and then we will retrieve it from EhCache.

Note – EhCache stores the data in In-Memory and Disk.

Maven Dependency.

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
</dependency>

Hibernate EhCache Configuration.

Step 1 – Enable second level cache and configure EhCacheRegionFactory(EhCacheProvider is deprecated). We need to make the below changes in the application.properties file.

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

Step 2 – Define ehcache.xml in the resources folder.

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">

<defaultCache eternal="false" timeToLiveSeconds="30"
memoryStoreEvictionPolicy="LRU" statistics="true" maxElementsInMemory="10000"
overflowToDisk="false" />

<cache name="book" maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="60" timeToLiveSeconds="60" memoryStoreEvictionPolicy="LRU"
statistics="true">
</cache>

</ehcache>

Step 3 – Use @Cacheable and @Cache annotation with the entity.

@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region = "book" )
public class Book implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int bookId;

@Column(name = "book_name")
private String bookName;

}

 

Hibernate/JPA EhCache Configuration Example Using Spring Boot and Oracle from Scratch(read-only).

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – hibernateehcache, ArtifactId – hibernateehcache and name – hibernateehcache) and click on finish. Keep packaging as the jar.

Modify pom.xml

 

If you see any error for oracle dependency then follow these steps.

Directory structure –

Hibernate/JPA EhCache Configuration Example

 

 

Student.java

StudentController.java

 

Note – See more details about @Controller and RestController here.

StudentRepository.java – interface

StudentService.java – interface

Note – See here more about @Component, @Controller, @Service and @Repository annotations here.

StudentServiceImpl.java

SpringMain.java

Note – See more details about @ComponentScan here.

JpaConfig.java

Note – See more details about @Configuration annotations here.

application.properties

 

The spring.jpa.properties.hibernate.cache.use_second_level_cache=true is used to enabled second level cache.

The spring.jpa.properties.hibernate.cache.use_query_cache=true is used to enable Query Cache.

spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory is EhCache provider.

ehcache.xml

 

Testing of example using postman.

Let’s run the SpringMain class(run as java application).

Perform save operation first using below REST API.

http://localhost:9091/book/savebook

{
    "bookName": "Alchemist"
}

Response Data.

Now perform get operation.

GET-  http://localhost:9091/book/1

 

Since we have defined time 60 seconds in ehcache.xml for the book, EhCache will store data in In-Memory for 60 seconds. For testing, hit the get URL(https://localhost:9091/book/1) multiple times from the postman and observe the console(since we have defined spring.jpa.show-sql = true in application.properties file query will print at the console) hibernate will not fire select query.

After 60 seconds if you again perform get operation, hibernate will fire the select query and for the next 60 seconds, you can retrieve data from the EhCache.

Note – Change the value of spring.jpa.properties.hibernate.cache.use_second_level_cache=false and restart the application and perform save operation. Now perform retrieve operation multiple times and observe the console. Hibernate will fire the query for each request since we have disabled the second level cache.

 

Hibernate/JPA EhCache example for Collection Types( OneToMany association).

In this section, we will see how to implement Hibernate/JPA EhCache for OneToMany association mapping. Suppose we have two entities Book and Story which are OneToMany relationship(one book can have many stories).

In this case below EhCache configuration and code change needed.

Define new cache for child(Story) entity in ehcache.xml.

<cache name="story" maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="20" timeToLiveSeconds="20"
memoryStoreEvictionPolicy="LRU" statistics="true">
</cache>

 

Entity level changes.

We need to define @Cache annotation with the child field(storyList).

@OneToMany(cascade = CascadeType.ALL, fetch= FetchType.LAZY)
@JoinColumn(name = "book_id",referencedColumnName="bookId")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region = "story" )
private List<Story> storyList = new ArrayList<>();

We need to use @Cacheable and @Cache annotation with the child entity(Story.java).

@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Story {

}

 

Book.java

 

Story.java

Note – The rest of the code would be the same.

HQL EhCache example(Enabling query cache).

We need to add spring.jpa.properties.hibernate.cache.use_query_cache=true in application.properties.

Defining the HQL method to retrieve the data.

@Transactional
public Book getBookUsingHQL(int bookId) {
String hql = "FROM Book b WHERE b.bookId = :bookId";
Query query = entityManager.createQuery(hql, Book.class);
query.setParameter("bookId", bookId);
query.setHint( "org.hibernate.cacheable", "true");
List<Book> books = query.getResultList();
return books.get(0);
}

Cache concurrency strategy in Hibernate.

There are four cache concurrency strategies supported by the hibernate.

  • Read-Only
  • Read-Write
  • Nonstrict-Read-Write
  • Transactional

 Read-Only cache concurrency strategy.

We have already seen CacheConcurrencyStrategy.READ_ONLY example. As the name suggests, this cache concurrency strategy is useful when we have to perform read-only operation. In this cache strategy if we will try to perform the update operation we might get java.lang.UnsupportedOperationException: Can't update readonly object.

@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = "book")
public class Book implements Serializable {

}

The read-only strategy is useful for search/retrieval operation.

Read-Write cache concurrency strategy.

Using CacheConcurrencyStrategy.READ_WRITE we can perform update operation too.

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Book implements Serializable {

}

Nonstrict-Read-Write Cache concurrency strategy.

Similar to read-write strategy but there might be occasional stale reads upon concurrent access to an entity.

@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Book implements Serializable {

}

Transactional cache concurrency strategy.

Provides serializable transaction isolation level.

@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class Book implements Serializable {

}

That’s all about Hibernate/JPA EhCache Configuration Example Using Spring Boot and Oracle.

You may like.

Spring Data JPA examples.

Hibernate association mapping using Spring Boot.

Hibernate EhCache documentation.

Summary – We have seen about Hibernate/JPA EhCache Configuration Example using Spring boot and Oracle.

Top