Spring @Cacheable methods with lists

我的梦境 提交于 2019-12-05 20:29:50

问题


I'm using latest Ehcache in my Spring 4.1.4 application. What I have is:

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 contacts are stored in the cache, and when I'm calling the getContactList method again, that all contacts whose id is already cached are retrieved from the cache and the other ones should be queried normally and then cached. This cache should then update the cached contact entity when it is updated.

I'm using plain Spring JDBC and Ehcache, no JPA and no Hibernate.


回答1:


Don't think that is possible. List<Integer> will be the key against the return value of getContactList will be saved in Cache.

So, unless the list of IDs that are being input to your getContactList contains exactly same IDs as in one of the previous calls, it will be a cache miss and data will be fetched from DB. (NOTE: Two lists are considered equal if they exactly contain same elements and in same order)

One option is to change your method getContactList(List<Integer> contactIdList) to getContact(Integer id) - in this case it may take a while to build cache, but once a Contact for a given ID is in cache, DB will not be used to re-fetch it in future calls.

Though not elegant, but another option is to do the caching manually in getContactList method.



来源:https://stackoverflow.com/questions/31220740/spring-cacheable-methods-with-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!