Hibernate L2 Cache with Spring Boot
What You Will Learn
How to configure Infinispan as the Hibernate second-level cache in a Spring Boot application using application.properties, and verify cache behavior through Hibernate statistics.
Prerequisites
-
Java 17+
-
Spring Boot
Step 1: Add Dependencies
Add Spring Boot Data JPA and the Infinispan Hibernate cache module to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-hibernate-cache-v66</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
Step 2: Configure Hibernate Caching in application.properties
Enable the second-level cache and query cache via Spring Boot properties:
# Enable those entities marked with @Cacheable to be cached
spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE
# Enables second level cache
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
# Enable query cache
spring.jpa.properties.hibernate.cache.use_query_cache=true
# Use Infinispan second level cache provider
spring.jpa.properties.hibernate.cache.region.factory_class=infinispan
# Force using local configuration when only using a single node.
# Otherwise a clustered configuration is loaded.
spring.jpa.properties.hibernate.cache.infinispan.cfg=org/infinispan/hibernate/cache/commons/builder/infinispan-configs-local.xml
# Entity specific configuration, e.g. via property:
# hibernate.cache.infinispan.<Entity FQN>.expiration.max_idle
spring.jpa.properties.hibernate.cache.infinispan.org.infinispan.tutorial.simple.hibernate.cache.spring.local.model.Person.expiration.max_idle=1000
# Generate statistics to see effects of second level cache
spring.jpa.properties.hibernate.generate_statistics=true
Step 3: Mark Entities as Cacheable
Annotate your JPA entities with @Cacheable:
@Entity
@Cacheable
public class Event {
@Id
@GeneratedValue
private Long id;
private String name;
private LocalDateTime timestamp = LocalDateTime.now();
Step 4: Run Cache Operations from a CommandLineRunner
The Spring Boot application uses a CommandLineRunner to demonstrate cache behavior:
@SpringBootApplication
public class InfinispanHibernateCacheSpringLocal {
private static final Logger log = LoggerFactory.getLogger(InfinispanHibernateCacheSpringLocal.class);
@Autowired
private EntityManagerFactory emf;
@Bean
public CommandLineRunner demo() {
Step 5: Run the Tutorial
mvn spring-boot:run
The output shows cache puts, hits, misses, and query cache statistics, confirming Infinispan is serving as the L2 cache provider.
What’s Next
-
Hibernate L2 cache standalone for the same pattern without Spring
-
Hibernate L2 cache with WildFly for a Jakarta EE deployment


