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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
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. :)