Search code examples
javaspring-boothibernatejpa

How to check if Hibernate is getting an object from the L1 cache?


I have a legacy application which in various places calls repository.findById(...) in a loop. This results in hundreds of calls to the database. Since Hibernate loads all entities into the L1 cache by default I thought I could fix this performance issue by calling repository.findByIdIn(...) before the loop and so save the repeated database calls. But I can't find a way to find if the entities were returned from the DB or the cache. Any ideas?


Solution

  • I am sorry to inform you that there are no APIs that can check if a given entity is loaded from L1 cache , L2 cache or DB.

    The most you can do is verify it from the log which configure the following loggers 's logging levels :

    • org.hibernate.event.internal.DefaultLoadEventListener to trace level
    • org.hibernate.SQL to debug level

    If the entity is loaded from DB , it will log out the SQL that is used to fetch this entity and :

     Object not resolved in any cache: [org.foo.bar.#1]
    

    If the entity is loaded from L2 cache , it will log out :

    Resolved object in second-level cache:[org.foo.bar.#1]
    

    If none of the above are logged , it means the entity is loaded from L1 cache.