Photo by insung yoon on Unsplash

What are Caching Levels in Hibernate?

Sriram Kumar Mannava
2 min readJan 30, 2024

--

Hibernate is a popular ORM for persistence in Java world. It implements the JPA specification and provides features that help working with relational databases using Java objects.

Caching Levels in Hibernate

Off the many features, we can add a caching perspective to the Hibernate ORM to persist frequently accessed data at the Hibernate level and return data when needed.

Hibernate offers two levels of caching - L1 Cache and L2 Cache.

L1 Cache is an in-memory caching layer that Hibernate uses to persist data. This is always enabled by default and is internal to Hibernate.

L1 Cache exists per session and is not shared among other threads.

L2 Cache is an optional caching layer on top of the L1 Cache, which is beyond Session scope.

It is a shared caching layer that allows external pluggable implementations. Moreover it is also shareable, which means if there are multiple threads that are querying over a dataset, they can benefit from this.

We can use any popular external caching provider as an L2 Cache integrated with Hibernate and store the frequently accessed datasets over here.

Since this is external to a session and is shareable, multiple services can query and share the cached data and help us reduce load over the backend.

We can use different cache providers for these purposes such as Ehcache, Apache Ignite, Infinispan, NCache etc.

Summary

  • Hibernate supports two levels of caching L1, L2
  • L1 cache is enabled by default and works inside a session scope, so not shareable
  • L2 cache is optional pluggable cache, which works out of scope, and is shareable
  • You can plugin an external cache as L2 and work with it

That was a brief explanation about Hibernate Cache levels.

--

--

Sriram Kumar Mannava
Sriram Kumar Mannava

Written by Sriram Kumar Mannava

I make Full Stack Development Easy for You | Full Stack .NET Dev | 3× AWS Certified | Blogger