To integrate Hibernate’s second-level cache with EHCache, follow these steps:
Step 1: Add Dependencies
Ensure that you have the required dependencies in your project:
For Maven:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.4.Final</version>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.10.8</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>6.0.0.Alpha7</version>
</dependency>
Step 2: Configure Hibernate for Second-Level Cache
Enable and configure the second-level cache in your application.properties
or hibernate.cfg.xml
file.
For application.properties (Spring-based projects):
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory
spring.jpa.properties.hibernate.javax.cache.provider=org.ehcache.jsr107.EhcacheCachingProvider
spring.jpa.properties.hibernate.cache.use_query_cache=true
For hibernate.cfg.xml
:
<hibernate-configuration>
<session-factory>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.jcache.JCacheRegionFactory</property>
<property name="hibernate.javax.cache.provider">org.ehcache.jsr107.EhcacheCachingProvider</property>
</session-factory>
</hibernate-configuration>
Step 3: Configure EHCache XML
Create a configuration file for EHCache, commonly named ehcache.xml
, and ensure it’s on your classpath (e.g., in src/main/resources
).
Example ehcache.xml
:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.ehcache.org/v3"
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">
<cache alias="default">
<expiry>
<ttl unit="seconds">3600</ttl>
</expiry>
<heap unit="entries">1000</heap>
<disk persistent="true" directory="java.io.tmpdir"/>
</cache>
<cache alias="com.example.entity.YourEntity">
<expiry>
<ttl unit="seconds">600</ttl>
</expiry>
<heap unit="entries">200</heap>
<disk persistent="true" directory="java.io.tmpdir"/>
</cache>
</config>
In this configuration:
- Each
cache
block configures a specific cache region. - The
heap
defines the maximum number of entries. - The
expiry
defines the time-to-live (TTL) for cache items.
Step 4: Enable Caching for Specific Entities
Annotate your entities to use the cache. Add the @Cache
annotation at the class level.
Example:
import jakarta.persistence.*;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Getters and Setters
}
Step 5: Enable Query Caching (Optional)
For query-level caching, explicitly enable it for specific queries.
Example:
Session session = sessionFactory.getCurrentSession();
Query<?> query = session.createQuery("from YourEntity where name = :name");
query.setParameter("name", "exampleName");
query.setCacheable(true);
Step 6: Test the Configuration
Test by loading entities multiple times and verifying that queries hit the cache instead of the database after the first load.
Keynotes:
- Concurrency Strategy: Use the appropriate
CacheConcurrencyStrategy
(e.g.,READ_WRITE
,NONSTRICT_READ_WRITE
) based on your needs. - Region Aliases: Define caching regions in your
ehcache.xml
and refer to those regions as needed. - Debugging: Enable Hibernate logging to verify cache usage:
logging.level.org.hibernate.cache=DEBUG
This setup ensures that Hibernate integrates with EHCache as its second-level cache provider effectively.