Date: March 18, 2025
In Part 1, we explored Hibernate’s first-level and second-level caches conceptually. Now, let’s get practical and integrate two popular caching providers — Ehcache and Redis — into Hibernate for second-level caching.
Why Integrate Caching Providers?
Hibernate itself defines caching APIs but relies on external providers for actual storage and management of cached data. Choosing the right cache provider can:
- Improve performance by reducing database hits
- Provide distributed caching for clustered environments
- Offer advanced features like expiration policies and statistics
1. Integrating Ehcache with Hibernate
Ehcache is a widely-used Java caching library known for simplicity and strong Hibernate integration.
Step 1: Add Ehcache dependencies
In your Maven pom.xml
:
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.10.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jcache</artifactId>
<version>5.6.0.Final</version>
</dependency>
Step 2: Configure Hibernate to use Ehcache (JCache)
In application.properties
:
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory
spring.cache.jcache.config=classpath:ehcache.xml
Step 3: Provide ehcache.xml
<ehcache:config xmlns:ehcache="http://www.ehcache.org/v3">
<ehcache:cache alias="com.example.model.User">
<ehcache:heap unit="entries">1000</ehcache:heap>
<ehcache:expiry>
<ehcache:ttl unit="minutes">15</ehcache:ttl>
</ehcache:expiry>
</ehcache:cache>
</ehcache:config>
Step 4: Annotate your entities
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User {
@Id
private Long id;
private String name;
// getters/setters
}
How it works:
When you load or update a User
entity, Hibernate caches it in Ehcache. Subsequent queries for that user within the TTL avoid hitting the database.
2. Integrating Redis with Hibernate
Redis, a popular in-memory key-value store, is useful especially when you want distributed caching across multiple app instances or microservices.
Step 1: Add Redis & Hibernate dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.19.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-redis</artifactId>
<version>5.4.27.Final</version>
</dependency>
Note: Hibernate doesn’t officially support Redis directly, but third-party providers like
hibernate-redis
or Redisson integration make it possible.
Step 2: Configure Redis connection in application.properties
spring.redis.host=localhost
spring.redis.port=6379
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.redisson.hibernate.RedissonRegionFactory
Step 3: Configure Redisson client
Create a redisson.yaml
config file:
singleServerConfig:
address: "redis://127.0.0.1:6379"
connectionMinimumIdleSize: 2
connectionPoolSize: 10
threads: 16
nettyThreads: 32
Then, register Redisson client as a Spring bean:
@Configuration
public class RedissonConfig {
@Bean(destroyMethod = "shutdown")
public RedissonClient redissonClient() throws IOException {
Config config = Config.fromYAML(new ClassPathResource("redisson.yaml").getInputStream());
return Redisson.create(config);
}
}
Step 4: Annotate entities (same as Ehcache)
Caching Considerations
- TTL and Eviction: Configure TTL (time to live) wisely to balance freshness and performance.
- Cache Consistency: Updates should invalidate or refresh cached data properly to avoid stale data.
- Clustered Environment: Redis excels in distributed cache scenarios; Ehcache can be clustered but needs additional configuration.
- Monitoring: Monitor cache hits/misses and tune cache sizes accordingly.
Summary Table
Feature | Ehcache | Redis |
---|---|---|
Storage | In-process JVM memory | Distributed in-memory |
Use case | Simple to moderate caching | Distributed caching & scaling |
Setup complexity | Moderate | Higher (extra network setup) |
Hibernate support | Official via JCache | Community/third-party |
Features | TTL, eviction policies | TTL, eviction, clustering |
Conclusion
Integrating Ehcache or Redis with Hibernate’s second-level cache can dramatically reduce database load and latency. For simple apps, Ehcache is easy and effective. For distributed or microservice architectures, Redis offers a powerful, scalable caching solution.
Next in this caching series:
Mastering Hibernate Caching – Part 3: Performance Tuning Using Cache Statistics