Spring3.1缓存注释EhCache

Spring3.1缓存注释EhCache,spring,ehcache,spring-annotations,Spring,Ehcache,Spring Annotations,我正在使用Spring3.1缓存,目前使用EhCache实现方法缓存。考虑下面的代码片段: @Cacheable("items") public Item findByPK(int itemID) { String sql = "SELECT * FROM ITEM WHERE ITEM_ID = ?"; Item item = getJdbcTemplate().queryForObject(sql, new Object[]{itemID}, new ItemRowMappe

我正在使用Spring3.1缓存,目前使用EhCache实现方法缓存。考虑下面的代码片段:

@Cacheable("items")
public Item findByPK(int itemID) {
    String sql = "SELECT * FROM ITEM WHERE ITEM_ID = ?";
    Item item = getJdbcTemplate().queryForObject(sql, new Object[]{itemID}, new ItemRowMapper());
    return item;
}

@Cacheable("items")
public List<Item> findAll() {
    String sql = "SELECT * FROM ITEM";
    List<Item> items = getJdbcTemplate().query(sql,new ItemRowMapper());
    return items;
}

如果我调用findByPK,它会先命中数据库,然后再命中缓存,因此方法缓存可以工作。芬德尔,同上。但是,有没有办法指示spring让findByPK调用识别findAll返回的结果

这是一个主要的黑客攻击,但它会为您提供所需的功能:

@Cacheable("items")
public Item findByPK(int itemID) {
    String sql = "SELECT * FROM ITEM WHERE ITEM_ID = ?";
    Item item = getJdbcTemplate().queryForObject(sql, new Object[]{itemID}, new ItemRowMapper());
    return item;
}

@Cacheable("items")
public List<Item> findAll() {
    String sql = "SELECT * FROM ITEM";
    List<Item> items = getJdbcTemplate().query(sql,new ItemRowMapper());
    for (Item item : items){
        removeThenAddToCache(item.getID(), item);
    }
    return items;
}

@CacheEvict(value = "items", key="#itemID")
public void removeThenAddToCache(int itemID, Item item) {
    addToCache(item);
}

@Cacheable(value = "items", key="#itemID")
public Item addToCache(int itemID, Item item) {
    return item;
}

这仅在您正在编织时有效,而在使用spring代理时无效;不确定我正在使用什么,如何检查?如何修复?如果尚未设置编织,则使用Spring默认的代理。如果不想设置编织,则可以将其分离到另一个组件中。。。但这将使它更像一个黑客。我通过反复给findAll上的findByPK打电话,得到了另一个正在工作的黑客,我很擅长这个…谢谢。