A Tip For Properly Utilizing Hibernate 2nd Level Cache

October 27, 2012

Your entity is @Cacheable, your cache is configured properly, but still, loading an entity produces a lot of sql queries. I noticed that the other day, and realized something: hibernate does not cache collection mappings. So if you have @OneToMany, they are fetched from the database. Which is a bit counter-intuitive, because my assumption was that hibernate caches the whole entity. This article explains what happens.

The solution is to use @Cache(..) (a hibernate-specific annotation) on all the collections.

What about lazy collections? Laziness serves a similar purpose – not to fetch data unnecessarily. But if you are actually using the collection, then for each collection a new query is sent. That’s why you need to annotate it with @Cache. Oh, and remember that generally you should avoid lazy JPA collections, and this caching problem is one more side-effect. Eager collections, of course, won’t help in this case, but if you didn’t have collections in the first place (most of them were unnecessary in our case), then you could spare a lot of queries, and also realize that they are not cached before you hit production performance problems.

One Response to “A Tip For Properly Utilizing Hibernate 2nd Level Cache”

  1. Hi

    Can you please help me in

    http://stackoverflow.com/questions/18895585/hibernate-version-annotation-and-object-references-an-unsaved-transient-instanc

Leave a Reply