1

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?

Mustahsan
  • 3,852
  • 1
  • 18
  • 34
Navs
  • 119
  • 1
  • 17
  • First level cache is associated to its session. For example if you were working in a session and you hit the same query twice, data will be retrieved from 1st Level cache, but when the session is closed, cached data are gone. – Akash Jun 12 '19 at 06:15
  • Please provide code where you are calling this method.Is the second call to the method in same transaction? – Jaspreet Jolly Jun 12 '19 at 06:23
  • @JaspreetJolly Yes, its in the same transaction. – Navs Jun 12 '19 at 06:32
  • As per my understanding,First level cache is default cache and there is no mechanism to disable it.So, only problem should be that call is made in 2 different sessions. – Jaspreet Jolly Jun 12 '19 at 06:36

2 Answers2

7

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

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
1

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

abendt
  • 675
  • 5
  • 9