0

As discussed in my previous post Too many mysql db call issue with spring boot rest service

I have followed https://www.baeldung.com/spring-cache-tutorial this tutorial and enabled hibernate second level caching and ehcache.

Example:

I have one table lets say product. I added @Cacheable("products") at the entity level.Also the findAll() method that calls this entity there too I made @Cacheable("getAllProductsCache").

First time after starting the server when I call this api, I see the queries getting executed, second time same api call does not show the queries (spring.jpa.show-sql: true).

However hibernate.generate_statistics: true -> this shows something strange, I dont see any hits on l2c. Which leads me thinking second time on wards the api call actually fetching data from db or l2c ?

2022-02-08 15:10:56.552  INFO 333476 --- [nio-8096-exec-2] i.StatisticalLoggingSessionEventListener : Session Metrics {
    931416 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    5761580 nanoseconds spent preparing 96 JDBC statements;
    123582139 nanoseconds spent executing 96 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    10440 nanoseconds spent executing 2 partial-flushes (flushing a total of 0 entities and 0 collections)
}
Tuhin Subhra Mandal
  • 473
  • 1
  • 5
  • 15
  • 1
    So you enable a caching mechanism outside the control of Hibernate and wonder why hibernate is not using the cache? Also I would strongly advice against using the Spring Cache abstraction for caching entities, you should really use the second-level and query cache in your JPA provider for that, as that is better equipped for that. – M. Deinum Feb 08 '22 at 10:16
  • Could you please share any reference to look at ? – Tuhin Subhra Mandal Feb 08 '22 at 10:22
  • 1
    You have configured Spring Cache, you cannot expect to see it in Hibernate statistics, it's two different things. If you want to configure L2C (Hibernate Second Level Cache), here an example: https://www.baeldung.com/hibernate-second-level-cache. (Moreover a findAll() query cannot be cached automatically in L2C, you need to add a query cache hint on your request) – Mickaël B. Feb 08 '22 at 12:55

0 Answers0