Enabling Second-Level (L2) Cache in Spring Boot with Hibernate
Introduction
Hibernate provides caching mechanisms to optimize database interactions and improve performance. It offers two levels of caching:
First-Level Cache (L1 Cache)
L1 cache is enabled by default and is associated with the Hibernate Session. It stores entities within the session scope, meaning the cached data is lost when the session is closed. This helps prevent multiple database calls within a single transaction.
Second-Level Cache (L2 Cache)
L2 cache, unlike L1 cache, is not enabled by default. It allows entity objects to be cached beyond the session scope, so multiple sessions can share cached data. This significantly reduces database queries and improves performance.
Query Cache
Hibernate also provides a query cache, which stores the result set of frequently executed queries to further optimize performance. This is separate from the entity cache and should be used along with the second-level cache.
1. Adding Dependencies
To enable Hibernate L2 caching, you need to add the dependency in your :
For Gradle users, add:
2. Configuring Hibernate Properties
In , enable the second-level cache and query cache:
If you are using , use:
3. Configuring Ehcache
Create an Ehcache XML configuration file named in :
4. Annotating Entities with @Cacheable
To enable caching at the entity level, use the annotation:
5. Enabling Cache in Queries
You also need to enable caching in your repository queries. If using , apply :
Alternatively, if using a , add a cache hint:
6. How L2 Cache Works Internally
When an entity is fetched from the database, Hibernate first checks if it is available in L1 cache (Session cache). If not found, it checks the L2 cache. If the entity is present in L2 cache, it is returned without querying the database. If it's not found in L2 cache, a database query is executed, and the entity is stored in L2 cache for future access.
L1 Cache: Stores entities for a single session.
L2 Cache: Stores entities beyond session scope, reducing DB hits.
Query Cache: Stores the result set of queries to optimize performance.
7. Verifying Cache
To check if L2 cache is working, monitor SQL queries. If you retrieve an entity twice and the SQL query only executes once, caching is effective.
Example:
If , you should see the SQL query only for the first execution, confirming cache usage.
Conclusion
Enabling Hibernate L2 cache in Spring Boot improves application performance by reducing database hits. By integrating Ehcache, configuring caching at the entity level, and using cache hints in queries, you can effectively leverage caching to optimize your application.
Happy coding!