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

A Tip For Properly Utilizing Hibernate 2nd Level Cache

DZone's Guide to

A Tip For Properly Utilizing Hibernate 2nd Level Cache

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

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.

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}