Search code examples
hibernatespring-dataehcache

How to force spring data to find entities for findAll method of CrudRepository in cache first, and only after in data sources


I have configured ehcache to work with hibernate and hibernate to work with spring-data and all frameworks work normally together. For example when I use method 'T findOne(ID var1);' of CrudRepository class, everything works fine, and the value is taken from a cache.

I expect that such behavior should be applicable to method 'Iterable findAll(Iterable var1);' because it should be easy to check for each particular id, if it is present in the cache, and then form query based on which id's are already found in cache and which are not. For example if I have items with id's {1,2,3} in cache and I try to invoke findAll({1,3,4,5}), the query should include only {4,5}. Also if I invoke findAll({1,3}) - no query to datasource should be done at all and all the data should be taken from cache.

These are my expectations. However in reality spring-data always form full request even in case all id's are already in cache. Any suggestions how to force the expected behavior?

ps: I know, that I can cache queries, however this case is quite different, I don't want to cache query by arguments, I want argument list to be treated as separate items, which could be taken from cache separately (but if some items need querying, it should be done by one query, not many!)


Solution

  • It seems it's not possible with basic spring-data jpa repository (jpa has no API for fetching by multiple ids for now).

    But you can try to

    Of course if you're using Hibernate 5.1+.

    It should manage L2 cache with MultiIdentifierLoadAccess.with mathod (https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/MultiIdentifierLoadAccess.html#with-org.hibernate.CacheMode-)

    Hope it helps.