Category Archives: Hibernate

Force refreshing second level cache in Hibernate

/** Vietnamese: cách xóa second level cache bằng code trong Hibernate**/

Hibernate second level cache is helpful, but only if using wisely.

In the ordinary context, if you delete an object in database by Hibernate, Hibernate will know and update its cache. But if the object/ tube got deleted by other programs (or by cascade delete set up in database itself), Hibernate won’t know and won’t update anything. Hence the deleted objects may remain in the cache for quite a time, and your code may throw an exception or two when trying to get items related to that object.

It’s a good practice to do every database-related thing through Hibernate. But in reality, sometimes we must do the other way around:

private void evict2ndLevelCache() {

  try {"Evicting all Entity Regions of 2nd Level Cache");
    Map classesMetadata = sessionFactory.getAllClassMetadata();
    for (String entityName : classesMetadata.keySet()) {"Entity from 2nd level cache:" + entityName);
  } catch (Exception e) {
  log.error("Error evicting 2nd level hibernate cache entities: ", e);


The solution provided here is an alternate of the solution in this question. Thanks brother Tinh for this information.