seon99il

Database

Hibernate Second-Level Cache with EhCache

3 min read

The time and cost of accessing the database over the network is much higher than the time to access the server’s internal memory. In this article, I will explain how to reduce the number of database accesses by caching data in memory.

Overview

As with most other fully-equipped ORM frameworks, Hibernate has the concept of a first-level cache. In this article we’ll explore the Hibernate second-level cache.

I will also explain the difference between the second-level cache and the first-level cache.

What is ORM (Object-Relational Mapping)?

Object-relational mapping (ORM) is a programming technique in which a metadata descriptor is used to connect object code to a relational database. Table : Entity (1:1)

ORM (Object-Relational Mapping)

Hibernate is one of the ORM frameworks.

About first-level cache

With JPA, the first-level cache is applied by default. It’s a session-scoped cache which ensures that each entity instance is loaded only once in the persistence context.

first-level cache

  1. Search for information by the user2 ID value userRepository.findById("userId")
  2. If there is information in the cache, the cached value is returned. If not, the information is retrieved from the DB. SELECT * FROM USER_INFO WHERE USER_ID = #{userId}
  3. The value is saved in the cache and returned
  • When Spring runs, it doesn’t cache all the data; only records per row are cached on select, update, delete, and save.
  • Once the session is closed, the first-level cache is terminated as well. This is actually desirable, as it allows concurrent sessions to work with entity instances in isolation from each other.

About second-level cache

Conversely, a second-level cache is SessionFactory-scoped, meaning it’s shared by all sessions created with the same session factory.

second-level cache

  1. Since there is no entity in the second-level cache at the time of the first lookup, it is queried from the DB.
  2. The result is saved in the second-level cache, and a copy of the entity is returned.
  3. When looking up the same entity, a copy of the entity is returned from the second-level cache.

Why use a second-level cache?

The second-level cache provides a copy of the query results to the persistence context. The reason is that even if multiple users modify the entity in the first-level cache, it does not affect the second-level cache, which is what is actually reflected.

This can be used to maximize concurrency.

Concurrency is a method for operating multiple threads on a single core, and refers to the property of multiple threads running alternately for multitasking. Single-core multitasking using concurrency looks like each thread is running in parallel, but in fact, they are running little by little in turn.

How to use second-level cache?

Java: 1.8

pom.xml

application.yml

## Enable @Cacheable annotation
spring.jpa.properties.javax.persistence.sharedCache.mode = ENABLE_SELECTIVE

## Enable second-level cache.
spring.jpa.properties.hibernate.cache.use_second_level_cache = true

## Specifies the class to handle the second-level cache.
spring.jpa.properties.hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory

## Check whether the cache is applied
spring.jpa.properties.hibernate.generate_statistics = true

resources/ehcache.xml

An .xml file can be used to set cache preferences. More settings are possible.

ItemEntity.java

After adding the Cacheable annotation, you are all set to enable the second-level cache. Check out the results now.

  • First request findById(1)

firstRequest

1 miss, because there is no value in the cache, and the value fetched from the DB is saved in the cache.

  • Second request (same entity) findById(1)

secondRequest

1 hit, because there is a value in the cache.

Previous posts

View all posts →

Comments