Search code examples
mongodbspring-bootdata-access-layer

Spring Boot - Avoid getting the same DAO multiple times


During writing a complex web application we realized that we often getting the same DAO during an API call. This can happen because of the fact that the application has multiple layers. We would like to avoid getting the same entity from the database multiple times during one request. The only solution which may be used would be the thread context. We could cache there the already requested entities from the database and the 2nd time when the system requests the same then it would be returned from the thread context instead of the database. This may work but all of us knows that it may not be the best option while the application can have background threads where this kind of caching would not be a good practice.

(We are using MongoDB if that's important)

If you know any other solution to this problem please let me know :)


Solution

  • Look into using the @Cachable notation and either use the default cache or you can implement any of a number of caching solutions that spring supports.

    https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/cache.html