Java.Hibernate.Middle.How do you evict an entity from the second-level cache?

Short Answer

You can evict a specific entity or entire cache regions from Hibernate’s second-level cache using the SessionFactory.getCache() API → this lets you remove stale or invalid entries manually.


🔎 Detailed Explanation

🔹 1) Evict a Specific Entity
To remove one entity instance from second-level cache:

SessionFactory sessionFactory = session.getSessionFactory();
sessionFactory.getCache().evictEntityData(MyEntity.class, entityId);

✅ This clears the cached data for the specific entity instance identified by its class + primary key.

🔹 2) Evict All Entities of a Class
To evict all cached instances of a given entity typ

sessionFactory.getCache().evictEntityData(MyEntity.class);

🔹 3) Evict an Entire Collection Cache
If you cache collections (e.g., a List of child entities in a one-to-many), you can evict:

sessionFactory.getCache().evictCollectionData("com.myapp.model.ParentEntity.children");

🔹 4) Evict the Entire Second-Level Cache
To clear everything → entities, collections, and query caches:

sessionFactory.getCache().evictAllRegions();

⚠️ Use with caution → this purges the whole second-level cache.

🧑‍💻 Example: Evict a Single Entity

// Assume you updated MyEntity in the database outside Hibernate
SessionFactory sf = session.getSessionFactory();
sf.getCache().evictEntityData(MyEntity.class, 42L); // evicts entity with ID 42

💡 Why manually evict?

✅ To clear stale data when an entity is updated outside Hibernate (e.g., raw SQL, another app).
✅ To force cache refresh for specific business scenarios (e.g., admin changes critical data).


📌 Key Takeaways

✅ Use SessionFactory.getCache().evictEntityData(...) to evict specific entities or all instances of a class.
✅ Manual eviction ensures cache consistency when data changes outside Hibernate.
✅ Be careful with broad evictions (e.g., evictAllRegions) → they clear all cached data, impacting performance temporarily.

This entry was posted in Без рубрики. Bookmark the permalink.