2

It is clear that, by default, when we execute entityManager.find(Post.class, 1L); then the Post instance for id=1 will be retrieved and placed in 1st level cache and then if we again execute the same entityManager.find(Post.class, 1L); in the same transaction, the post instance will be returned directly from 1st level cache without querying the database.

My question is the following:

Is the 1st level cache checked only when we try to get the entity by id executing entityManager.find(...); method ? I mean what if we fetch the same Post instance(having id = 1) by different property other than ID, e.g. using Criteria query fetching the post by name ? Is it still going to check the 1st level cache ?

What about querying the same row by native query, jpql or spring data query method ? Does JPA/Hibernate parse native query and jpql queries in order to find out if there is a corresponding entity in 1st level cache ?

Suren Aznauryan
  • 984
  • 10
  • 24
  • The L1 cache would be checked on any retrieval, clearly, since you can only have 1 object with a particular "id" in the persistence context –  Oct 29 '18 at 08:56
  • Possible duplicate of [JPA EntityManager caching](https://stackoverflow.com/questions/8878422/jpa-entitymanager-caching) – K.Nicholas Oct 29 '18 at 17:36
  • Better write a small unit-test and turn on sql logging. Then you can easyly check yourself. :-) – B_St Oct 30 '18 at 14:29

0 Answers0