✅ Short Answer
You can monitor Hibernate’s second-level cache statistics using the Hibernate Statistics
API, which tracks cache hits, misses, and puts for entities, collections, and queries.
🔎 Detailed Explanation
🔹 1) Enable Hibernate Statistics
First, you must enable statistics collection — either in your configuration:
hibernate.generate_statistics=true
or programmatically:
sessionFactory.getStatistics().setStatisticsEnabled(true);
🔹 2) Access the Statistics API
You can obtain statistics via SessionFactory.getStatistics()
:
Statistics stats = sessionFactory.getStatistics();
🔹 3) Get Cache Statistics
Hibernate exposes global and per-entity/region statistics:
✅ Global cache hits/misses
long hits = stats.getSecondLevelCacheHitCount();
long misses = stats.getSecondLevelCacheMissCount();
long puts = stats.getSecondLevelCachePutCount();
✅ Per-cache-region statistics
SecondLevelCacheStatistics regionStats = stats.getSecondLevelCacheStatistics("com.myapp.model.MyEntity");
System.out.println("Hits: " + regionStats.getHitCount());
System.out.println("Misses: " + regionStats.getMissCount());
System.out.println("Puts: " + regionStats.getPutCount());
🔹 4) Example: Print Statistics
Statistics stats = sessionFactory.getStatistics();
System.out.println("Second-level cache hits: " + stats.getSecondLevelCacheHitCount());
System.out.println("Second-level cache misses: " + stats.getSecondLevelCacheMissCount());
System.out.println("Second-level cache puts: " + stats.getSecondLevelCachePutCount());
🔹 5) Expose Metrics in Spring
In a Spring Boot environment, you can expose these statistics:
- Periodically log them with a scheduled task.
- Export them to Prometheus/Grafana via Micrometer by integrating
SessionFactory.getStatistics()
data.
📊 Key Metrics
Metric | Meaning |
---|---|
SecondLevelCacheHitCount | Cache lookups that found valid data |
SecondLevelCacheMissCount | Lookups where cache didn’t have the data |
SecondLevelCachePutCount | New/updated entries added to cache |
📌 Key Takeaways
✅ Enable Hibernate statistics (hibernate.generate_statistics=true
) to collect cache hit/miss info.
✅ Use SessionFactory.getStatistics()
to access global and per-region cache metrics.
✅ Monitoring these stats helps you tune caching strategy and identify performance bottlenecks.