Getting Started with Hazelcast and Hibernate Second-Level Cache

See something wrong? Edit this page.

This guide will get you started to use Hazelcast in a Spring Boot application. You can see the code sample here.

What You’ll Learn

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


  • ~10 minutes

  • 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 second-level cache provider, you need to add two dependencies:



And then, we need to configure Hazelcast IMDG local member setting by adding a standard hazelcast.xml file into src/main/resources.

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 into file:

And now, once 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, we bootstrapped a Spring Boot application which uses Hazelcast as Hibernate’s second-level cache.