javahibernatejpaspring-data-jpafirst-level-cache

Hibernate first level cache is missed


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?


Solution

  • 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