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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Published at DZone with permission of Bozhidar Bozhanov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}