Hibernate first level cache is missed

2.4k Views Asked by At

I'm a newbie to JPA/Hibernate first level caching.

I have the following repository class

Each time I call the findByState method(within the same transaction), I see the hibernate sql query being output onto the console

public interface PersonRepository extends JpaRepository<PersonEntity, id> {

    @Query("select person from PersonEntity p where name= (?1)")
    List<PersonEntity> findByState(String state);
    ....
}

I expected the results to be cached by the first level cache and the database not be repeatedly queried.

What am I doing wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

There is often a misunderstanding about caching.

Hibernate does not cache queries and query results by default. The only thing the first level cache is used is when you call EntityManger.find() you will not see a SQL query executing. And the cache is used to avoid object creation if the entity is already loading.

What you are looking for is called "query cache".

This can be enabled by setting hibernate.cache.use_query_cache=true

Please read more about this topic in the official documentation:

https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#caching-query

0
On

The query will always go to the database. The first level cache will only contain the constructed entities. Its purpose is to ensure that the same db id is mapped to the same entity object (within a session) Its also possible to use a query cache. You have to enable per query. Check the docs https://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch06.html