Performance Zone is brought to you in partnership with:

Senior Java developer, one of the top stackoverflow users, fluent with Java and Java technology stacks - Spring, JPA, JavaEE. Founder and creator of http://computoser.com and http://welshare.com . Worked on Ericsson projects, Bulgarian e-government projects and large scale recruitment platforms. Member of the jury of the International Olympiad in Linguistics and the Program committee of the North American Computational Linguistics Olympiad. Bozhidar is a DZone MVB and is not an employee of DZone and has posted 87 posts at DZone. You can read more from them at their website. View Full User Profile

A Tip For Properly Utilizing Hibernate 2nd Level Cache

11.07.2012
| 6703 views |
  • submit to reddit

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.

Published at DZone with permission of Bozhidar Bozhanov, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)