Over a million developers have joined DZone.
Gold Partner

A Tip For Properly Utilizing Hibernate 2nd Level Cache

· Java Zone

The Java Zone is brought to you in partnership with Azul Systems.   Discover how to stop tuning and get back to coding with Azul Zing.

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.

The Java Zone is brought to you in partnership with Azul Systems.   Discover how to stop tuning and get back to coding with Azul Zing.

Topics:

Published at DZone with permission of Bozhidar Bozhanov , DZone MVB .

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}