Get Started with Hazelcast and Hibernate Second-Level Cache

What You’ll Learn

In this tutorial, you’ll learn how to quickly set up a Spring Boot application using Hazelcast as a Hibernate second-level cache.

Before you Begin

  • A text editor or IDE

  • JDK 1.8+

  • Apache Maven 3.2+

In order to run the code sample, make sure to have PostgresSQL database accessible and configured properly in the file.

You can spin-up a PostgreSQL instance easily using Docker:

docker run --name 2lc-postgres --publish 5432:5432 -e POSTGRES_PASSWORD=mysecretpassword -d postgres:13


In order to enable JPA, you need to add a dedicated Spring Boot Starter:


In order to configure Hazelcast as a second-level cache provider, you need to add two dependencies:


And then, you need to configure the Hazelcast member setting by adding a standard hazelcast.xml file into src/main/resources directory.

Keep in mind that this might trigger the autoconfiguration of another Hazelcast member so you might want to disable Hazelcast autoconfiguration:

@SpringBootApplication(exclude = HazelcastAutoConfiguration.class)

The last step involves turning on second-level cache by adding two properties in the file:

And now, after you annotate your entity as @Cacheable, it will be cached in Hazelcast member:

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

Running the Application

Run the application by executing the following command.

mvn spring-boot:run

You should see in logs that Hazelcast members started successfully.

Members {size:1, ver:1} [
        Member []:5701 - f3984396-0ec9-40c8-861e-cb34f14d7204 this

What happens then is that an object is saved to the database and then fetched. In the meantime, the object is stored in the second level cache. SecondLevelCacheVisualizer prints out the L2C content in every 10 seconds.

size: 1
    com.hazelcast.hibernate.springhibernate2lc.persistence.Book#1:read-write Item(CacheEntry(com.hazelcast.hibernate.springhibernate2lc.persistence.Book))

size: 1
    com.hazelcast.hibernate.springhibernate2lc.persistence.Book#1:read-write Item(CacheEntry(com.hazelcast.hibernate.springhibernate2lc.persistence.Book))

The object is then evicted from the L2C after 30 seconds, which is the configured time-to-live in hazelcast.xml.

size: 0


In this guide, you bootstrapped a Spring Boot application to use Hazelcast as a Hibernate second-level cache.