Java.Hibernate.Medium.How can i evict entity from Hibernate Cache in Spring enviroment ?

Short Answer

In a Spring environment, you evict an entity from the second-level cache by accessing the SessionFactory bean (from your JPA/Hibernate integration) and calling getCache().evictEntityData(...).

🔎 Detailed Explanation

🔹 1) Obtain the SessionFactory
If you use Spring Boot with Hibernate JPA, you can inject the EntityManagerFactory and unwrap it to get the native SessionFactory:

import jakarta.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

@Service
public class CacheEvictionService {

    private final SessionFactory sessionFactory;

    public CacheEvictionService(EntityManagerFactory emf) {
        this.sessionFactory = emf.unwrap(SessionFactory.class);
    }

    public void evictEntity(Class<?> entityClass, Object id) {
        sessionFactory.getCache().evictEntityData(entityClass, id);
    }
}

🔹 2) Use the service to evict entities
Example usage (e.g., inside a Spring REST controller or service):

// Evict a specific entity with ID=42
cacheEvictionService.evictEntity(MyEntity.class, 42L);

🔹 3) Other Eviction Methods
✅ Evict all instances of an entity:

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

✅ Evict the entire second-level cache:

sessionFactory.getCache().evictAllRegions();

🔹 4) Why unwrap EntityManagerFactory?

  • In Spring, EntityManagerFactory is the standard JPA interface.
  • But to use Hibernate-specific APIs (like second-level cache eviction), you need the native Hibernate SessionFactory.
  • emf.unwrap(SessionFactory.class) gives you direct access.

📌 Key Takeaways

✅ In Spring, inject EntityManagerFactory, then unwrap to SessionFactory to access Hibernate cache APIs.
✅ Use sessionFactory.getCache().evictEntityData(...) to manually evict entities from the second-level cache.
✅ This approach ensures Spring-friendly, programmatic cache management.

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

Leave a Reply

Your email address will not be published.