Caching is a mechanism to enhance the performance of the system. It’s a buffer memory that lies between app & DB. Cache memory stores the recently used data items in order to reduce the number of DB hits as much as possible.

First Level Cache :
First level cache is associated with session.The scope of cache objects is on the session. Once the session is closed the cached objects will gone forever. First level cache is enabled by default you cannot disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.
Course course1 = repository.findById(10001L);
logger.info("First course retrieved {}");
Course course2 = repository.findById(10001L);
logger.info("First course retrieved again {}");
If we access same findById() method after first time. Hibernate will not execute select query it will fetch if from first level cache.
It is necessary to annotate @Transactional at the method level otherwise two consecutive select queries will execute if we have two findById() transactions.
Second Level Cache :
One of the major benefit of using hibernate in large application is its support of first and second level of caches.
Hibernate second level cache uses a common cache for all the session object of a session factory. It is useful if you have multiple session objects from a session factory. SessionFactory holds the second level cache data. It is global for all the session objects and not enabled by default.
Ex : EH Cache, Redis

Hibernate EH cache :
In this article we use EH Cache as a cache provider. EH cache is the best choice for second level cache in hibernate.
We add the EHCache region factory implementation to the class-path with the following dependency on your pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.2.2.Final</version>
</dependency>
In application.yml the following properties should implement:
hibernate.cache.use_second_level_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
In order to make an entity as cacheable we need to annotate that with org.hibernate.annotations.Cache
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private long id;
@Column(name = "NAME")
private String name;
}
For each entity class, Hibernate will use a separate cache region to store state of instances for that class. The region name is the fully qualified class name.
For example, Course instances are stored in a cache named com.test.model.Course in Ehcache.

Leave a comment