Clearing Hibernate's Second-Level Cache
Monday, 18 February 2008 00:00

Hibernate is a popular open source tool for O/R mapping. One of the benefits of using Hibernate is the ability to easily and automatically cache data pulled from the database. Hibernate uses two different levels of cache. The first level is always on and caches data within a given session. The second level must be explicity enabled and caches data on an on-going basis between different sessions.

Sometimes, a situation may arise where you wish to clear out Hibernate's second level cache. For example, you may make a direct update to your database by manually running SQL. In these cases, it would be nice to have a generic method that would clear out the entire second level cache to make sure the updates are reflected in your Java application.

However, it seems that the methods that are provided by Hibernate only allow clearing very specific sections of the second level cache. As such, I had to put together the following method which should do the trick of completely clearing out the entire second level cache:

public void evictSecondLevelCache() {
  Map<String, CollectionMetadata> roleMap = factory.getAllCollectionMetadata();
  for (String roleName : roleMap.keySet()) {
    factory.evictCollection(roleName);
  }

  Map<String, ClassMetadata> entityMap = factory.getAllClassMetadata();
  for (String entityName : entityMap.keySet()) {
    factory.evictEntity(entityName);
  }

  factory.evictQueries();
}