Spring @ Cacheable Listing Methods

I am using the latest Ehcache in my Spring 4.1.4 application. I have:

class Contact{ int id; int revision; } @Cacheable("contacts") public List<Contact> getContactList(List<Integer> contactIdList) { return namedJdbc.queryForList("select * from contact where id in (:idlist)", Collections.singletonMap("idlist", contactIdList)); } @CachePut(value="contact", key = "id") public void updateContact(Contact toUpdate) { jdbctemplate.update("update contact set revision = ? where id = ?", contact.getRevision(), contact.getId()); } 

What I want to achieve is that the contacts are stored in the cache, and when I call the getContactList method getContactList , all contacts whose id already cached are retrieved from the cache, and others should be requested in normal mode and then cached. This cache then updates the cached contact entity when it is updated.

I use simple Spring JDBC and Ehcache, no JPAs and no hibernation.

+8
spring jdbctemplate ehcache
source share
1 answer

Do not think it is possible. List<Integer> will be the key to the return value of getContactList , it will be stored in the cache.

So, if the list of identifiers that are entered in your getContactList does not contain exactly the same identifiers as in one of the previous calls, this will be a cache miss and the data will be extracted from the database. (NOTE: Two lists are considered equal if they exactly contain the same elements and in the same order)

One option is to change your getContactList(List<Integer> contactIdList) to getContact(Integer id) - in this case, it may take some time to create a cache, but once the contact for this identifier is in the cache, the database will not be used to reuse, select it in future calls.

Although not elegant, yet another option is to manually cache using the getContactList method.

0
source share

All Articles