首页 文章

Spring 3.1 Cache Annotation EhCache

提问于
浏览
0

我目前正在使用Spring 3.1 Cache使用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()它首先命中数据库,然后它就会命中缓存,因此方法缓存有效 . findAll()同上 . 但是,有没有办法指示spring使findByPK()调用识别findAll()返回的结果?

1 回答

  • 1

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

    @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;
    }
    

相关问题