-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Mybatis will cache query results for each individual query. So if you call findAllProducts()
then only that list of products will be cached; ie: future queries to findAllProducts()
will return the cached results. If you call findProductById(123)
then it will kick off another query to the database, even if product with ID 123 was one of the results returned in findAllProducts()
.
When I retrieve a set of results I'd like to know that I could add results to the cache based on a number of associated item properties. So, for our example above, I'd like to know that when I cache all products that I can also cache each of those products by their id and code.
In the past, in order to cache results we've had to write our own wrappers which live outside/above mybatis in order to reduce database access, eg: a CachedProductMapper
which uses an underlying ProductMapper
to run findAllProducts()
and then create a Map in CachedProductMapper
based on ProductId -> Product. Each subsequent call to findProductById()
would then look up the product in that map.
That's fine in that it removes calls to the database whenever findProductById()
is called. By what happens when we want to retrieve a product as an associated property, for example within an Order? We either have to include it in one big ResultMap or as a separate Select. In this case we would prefer to look it up in a separate Select, and have it use the cache to find the product.
- Less object creation - the cache is used instead of having to create a new object via a ResultMap or Select
- Smaller result sets returning from the database due to not having to define combined ResultMaps
- Simpler reasoning about what is truly cached due to caching being done at the correct level, ie: in mybatis
- Less code - no need to write custom wrappers
Take a look at Usage for details as to how to set up the cascading cache.
- Still in it's infancy
- Only tested with read-only caches - being used for reference data lookups