lapots
lapots

Reputation: 13395

does spring data jpa do caching

I've got a simple repository that looks like this

public interface PlayerLevelRepository extends CrudRepository<PlayerLevel, Integer> {
    @Query("FROM PlayerLevel WHERE exp <= :exp ORDER BY exp DESC")
    List<PlayerLevel> findClosestToExperienceLevel(@Param("exp") long exp);
}

I was analyzing the response time from rests and saw that the first rest execution was ten times slower than the next.

So I decided to check the time of repository method (I don't have any other time consuming actions there) like this

@Override
public int findClosestLevel(long exp) {
    long startTime = System.nanoTime();

    int closestLevel = levelRepository.findClosestToExperienceLevel(exp).get(0).getLevel();

    long endTime = System.nanoTime();
    LOGGER.info("Execution time: {}", endTime - startTime);
    return closestLevel;
}

And I saw that the first invocation spends 35012440 aka 35 ms. Second, third and other invocations spend ten times less time - 2194712 or 2ms, 3058421 or 3ms and so on.

My question is - does Spring Data JPA cache query results of something?

Upvotes: 1

Views: 1090

Answers (1)

Arek
Arek

Reputation: 3176

Spring Data JPA is "just" a wrapper (or a nice facade) over JPA, so underneath you still have standard JPA capabilities. You have 1lvl cache on the EntityManager / Session level, and 2lvl cache on EntityManagerFactory / SessionFactory level. There are more types of cache, like: query result cache etc. You can read more about them here (it's for older Hibernate version, but it should still be valid).

Upvotes: 4

Related Questions