Hibernate Tutorial
Core Hibernate
Hibernate Mapping
Hibernate Annotations
Hibernate with Spring Framework
Hibernate with Database
Hibernate Log4j
Inheritance Mapping
In Hibernate, caching is a mechanism that allows you to store frequently accessed data in memory so that you don't have to hit the database every time you need that data. Cache eviction refers to the removal of objects from the cache, either manually or automatically.
Hibernate provides two levels of caching:
First Level Cache (Session Cache): This is enabled by default and exists for the duration of a session. Objects in the session cache are automatically evicted when the session is closed or cleared.
Second Level Cache (SessionFactory Cache): This is an optional cache that exists for the duration of the SessionFactory
. You can integrate third-party caching providers like EHCache, Hazelcast, etc., to use this feature.
Let's go through an example that demonstrates cache eviction using Hibernate and EHCache as a second-level cache provider.
Add the EHCache and Hibernate EHCache integration dependencies to your pom.xml
.
<!-- EHCache core library --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.6</version> </dependency> <!-- Hibernate EHCache integration --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>5.4.32.Final</version> </dependency>
In your hibernate.cfg.xml
:
<property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
In your entity class, enable caching and specify cache eviction strategies.
@Entity @Table(name = "student") @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Student { // class content }
In this case, we're using a READ_WRITE
strategy, which allows both reads and writes with proper handling to maintain cache consistency.
Automatic Eviction: Based on the eviction strategy and configuration, Hibernate will automatically evict cache entries. For instance, if the cache is full and a new entity needs to be cached, an old entity will be evicted automatically.
Manual Eviction: If you know that specific data has changed and want to remove an entity or collection from the cache manually:
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); // Evict a specific entity from the session (first-level) cache session.evict(student); // Evict all entities of type Student from the second-level cache sessionFactory.getCache().evictEntityRegion(Student.class); tx.commit(); session.close();
In the ehcache.xml
file, you can set specific cache settings:
<ehcache> <diskStore path="java.io.tmpdir/ehcache" /> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"> </defaultCache> <cache name="com.example.Student" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true"/> </ehcache>
This configuration sets global default settings and specific settings for the Student
entity cache. The timeToIdleSeconds
and timeToLiveSeconds
attributes help in automatic eviction based on the age or idle time of cached data.
Remember, caching adds complexity to the application. Use it wisely and only for entities or collections that benefit from caching in terms of performance. Always monitor cache hit/miss ratios to understand if your cache configuration is effective.
Hibernate second-level cache eviction example:
Hibernate second-level cache eviction involves removing entities or collections from the cache to refresh them with updated data.
Session session = sessionFactory.openSession(); session.getSessionFactory().getCache().evictEntityRegion(MyEntity.class); session.close();
Cache eviction strategies in Hibernate:
Hibernate supports various cache eviction strategies, including LRU (Least Recently Used) and FIFO (First In, First Out).
<!-- Configure cache eviction strategy in hibernate.cfg.xml --> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <property name="hibernate.cache.ehcache.eviction_policy">LRU</property>
Evicting specific entities from Hibernate cache:
Evict specific entities from the cache using evictEntity
method.
Session session = sessionFactory.openSession(); session.getSessionFactory().getCache().evictEntityRegion(MyEntity.class, entityId); session.close();
Programmatic cache eviction in Hibernate:
Programmatically evict entities or collections from the cache based on certain conditions.
Session session = sessionFactory.openSession(); Cache cache = session.getSessionFactory().getCache(); if (condition) { cache.evictEntityRegion(MyEntity.class, entityId); } else { cache.evictCollectionRegion(MyEntity.class.getName() + ".myCollection", entityId); } session.close();
Configuring time-based cache eviction in Hibernate:
Configure time-based cache eviction to automatically refresh the cache after a certain period.
<!-- Configure time-based eviction in hibernate.cfg.xml --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <property name="hibernate.cache.ehcache.timeToLiveSeconds">60</property>
Hibernate cache region eviction:
Evict entire cache regions to remove all entities or collections associated with a specific region.
Session session = sessionFactory.openSession(); session.getSessionFactory().getCache().evictQueryRegions(); session.close();
Cache eviction policies in Hibernate:
Hibernate supports various eviction policies such as READ_ONLY
, NONSTRICT_READ_WRITE
, and READ_WRITE
.
<!-- Configure eviction policies in hibernate.cfg.xml --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <property name="hibernate.cache.ehcache.eviction_policy">READ_ONLY</property>
Evicting collections from Hibernate cache:
Evict specific collections from the cache using evictCollection
method.
Session session = sessionFactory.openSession(); session.getSessionFactory().getCache().evictCollectionRegion(MyEntity.class.getName() + ".myCollection", entityId); session.close();
Monitoring cache eviction in Hibernate:
Monitor cache eviction by enabling cache statistics and accessing eviction-related metrics.
SessionFactory sessionFactory = configuration.buildSessionFactory(); Statistics stats = sessionFactory.getStatistics(); stats.setStatisticsEnabled(true); // Access eviction-related metrics long entityEvictions = stats.getEntityRegionEvictCount();