This might be a very general question. I want to know if caching (first level cache and second level cache) is this the only way to reduce the number of db hits in Hibernate.
CodePudding user response:
Your question is very generic, however at a high level yes caching will solve multiple database hit problem. You can use hibernate caching also you can also use Spring Cache Abstraction for a fine grained implementation. There are other aspects also and that depends on your problem statement and solution approach.
Remember: Any caching will increase your memory uses in application and also you need to clean cache appropriately to avoid any stale information being used.
CodePudding user response:
Reducing a number of DB queries can be divided into 2 steps:
- Eliminating possible N 1 problem sources.
- Looking for hot spots in the application, what data is nedeed the most often and cache it by various means.
The former could be done with @Fetch(FetchMode.SUBSELECT), JPQL/HQL JOIN FETCH and JPA entity graphs. For the latter you can use Spring caching possibilities or Hibernate-specific caching.