Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Clearing Hibernate Second-Level Caches

DZone's Guide to

Clearing Hibernate Second-Level Caches

· Database Zone
Free Resource

MongoDB Atlas is a database as a service that makes it easy to deploy, manage, and scale MongoDB. So you can focus on innovation, not operations. Brought to you in partnership with MongoDB.

Recently, I wanted to be able to clear out all of the Hibernate caches via JBoss's JMX console. I could have taken the easy way out; we're using EHCache, so it could have been as simple as calling CacheManager.clearAll(). However, that would have tied me to a specific cache provider. We're still evaluating switching to other cache providers. Ideally, my solution would not be dependent on a specific cache implementation.

Hibernate's API does provide a simple way to clear specific caches, but does not provide any method for clearing out all of them. Writing your own is fairly straightforward. First, you obtain all of the entity and collection metadata from the session factory. Next you iterate over the entities, and if the object is cached, you clear out all of the caches associated with the persisted class or collection. Here's the code:

  @PersistenceContext  private EntityManager em;  public void clearHibernateCache() {      Session s = (Session)em.getDelegate();      SessionFactory sf = s.getSessionFactory();         Map classMetadata = sf.getAllClassMetadata();      for (EntityPersister ep : classMetadata.values()) {          if (ep.hasCache()) {              sf.evictEntity(ep.getCache().getRegionName());          }      }         Map collMetadata = sf.getAllCollectionMetadata();      for (AbstractCollectionPersister acp : collMetadata.values()) {          if (acp.hasCache()) {              sf.evictCollection(acp.getCache().getRegionName());          }      }         return;  }

Now, if we decide to switch to a different cache provider, this code will not need to be re-written. Hopefully we won't ever change to a different JPA implementaion. :)

From http://mikedesjardins.us/blog/

 

MongoDB Atlas is the best way to run MongoDB on AWS — highly secure by default, highly available, and fully elastic. Get started free. Brought to you in partnership with MongoDB.

Topics:
java ,sql

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}