Reputation: 2546
I'm using EhCache(2.10.1) and Spring (4.2.5)
I configured my BookDao's methods with cache like this:
@Cacheable(value = "bookByName", key = "#name")
public Book findByName(String name) {
//find book by name in db
}
@Cacheable(value = "bookById", key = "#id")
public Book findById(int id) {
//find book by id in db
}
@Cacheable(value = "books", key = "??")
public List<Book> findAll() {
//find books in db
}
First, would it be possible to combine findAll
cache with findById
cache or findByName
cache? What should I put in the key annotation parameter
to do so?
Second, if I want to update or create one book I need to add/evict this book on each cache and evict the entire list of the findAll
method. Is there another way to do this better?
Upvotes: 0
Views: 295
Reputation: 5723
Answering on a conceptual level. It is basically the identical problem for any cache as well as for Spring caching annotations or JSR107 caching annotations.
First, would it be possible to combine
findAll
cache withfindById
cache orfindByName
cache? What should I put in the key annotation parameter to do so?
No, this isn't possible with annotations. Except clearing the cache, you cannot do bulk operations with annotations.
One possibility would be to retrieve all entries in the cache using the imperative cache interface, however, that's only the books in the cache, not all available books. The cache doesn't know every book that is available, at least if it is really a cache.
Second, if I want to update or create one book I need to add/evict this book on each cache and evict the entire list of the
findAll
method. Is there another way to do this better?
If you have a list of all books, what do you need the cache for?
You could return a subset of all books in a list. In this case the parameter could be a query. The list size should be limited, so you do not run out of memory while processing and when caching it. Ideally you return
List<Integer>
with the ids or a List<Book>
that is backed with an id array and retrieves the book objects from the cache.
If you want to be able to process all books then a method Iterator<Integer> findAll()
or Iterator<Book> findAll()
would be more appropriate. You shouldn't cache it, because: the result size is unbounded, the cache makes only sense when small parts of the data is accessed more often.
Upvotes: 2