Avoiding Multiple Data Fetches Using the First-Level-Cache in Spring Data JPA
If you’re dealing with backend development on the JVM, you’ll surely come across the Java Persistence API (JPA). A well-known implementation framework for it is Hibernate. In this article, we’ll show you how you can optimize the performance of your application in Spring Data JPA with caching by preventing the same resources from being fetched multiple times.
What is the First-Level-Cache?
Spring Data JPA uses Hibernate as the default ORM (Object-Relational Mapping), which provides an inbuilt First-Level-Cache. Each session has its own cache, which we refer to as the First-Level-Cache. Every time you retrieve an object (or more precisely, an entity instance) from the database, it is first stored in the First-Level-Cache. When retrieving the same object again, it is fetched directly from the cache and not from the database. This can lead to data repetition and impair performance.