Raj R
Raj R

Reputation: 63

Cache and Improve performance of JpaRepository method

I have the below code.I am using SPRING BOOT and JAVA 8

@Repository
public interface LogRepository  extends JpaRepository<Log, Integer>{



    List<Log> findByDate( Date date) ;

findByDate is returning me suppose 1 million records.findByDate( Date date) method gets fired whenever user is hitting the url /api/get/logs.

How can I keep the data in cache ?I don't want to hit the database every time method findByDate( Date date) is called.

Upvotes: 1

Views: 1828

Answers (2)

Ludovico Sidari
Ludovico Sidari

Reputation: 67

Here a great guide about caching and eviction in spring boot https://www.baeldung.com/spring-cache-tutorial. However, you shouldn’t cache 1000000 records from a single query. It’s too expensive and you may risk a socketTimeoutException or a 502 timeout from client/application server. You should implement pagination on your Services (already provided by JPA itself) and eventually cache the pages (pay attention to the updates - take also a look at cache merging annotations)

Upvotes: 1

Sounak Saha
Sounak Saha

Reputation: 933

Step 1: You need to add @EnableCaching annotation with @SpringBootApplication in your main class.

Step 2: Add @Cacheable annotation in your method like below

@Cacheable(value="user", key="#date")     
User findByDate( Date date) ;

For more details regarding the different cache configuration, you can follow be https://howtodoinjava.com/spring-boot2/spring-boot-cache-example/

Upvotes: 1

Related Questions