Spring 缓存 - 只缓存一些表

Spring Cache - Only cache some tables

我想在我的应用程序中缓存一些数据库 table,因为 table 中的内容每天只更新一次。

我让 Spring 缓存像这样工作:

@Service("stuffManager")
public class StuffManagerImpl implements StuffManager {

    @Autowired
    private StuffDao stuffDao;

    @Override
    @Cacheable("stuffCache")
    public List<Stuff> getAllStuff() {
        return stuffDao.getAllStuff();
    }
}

@Repository("stuffDao")
public class StuffDaoHibernate implements StuffDao {

    @Override
    public List<Stuff> getAllStuff() {
        return getHQLResult("select* from Stuff", null);
    }
}

但是,如果我的 getAllStuff 方法看起来像这样,但我只想缓存 Stuff-table,是否可以使用 Spring 缓存?

@Repository("stuffDao")
public class StuffDaoHibernate implements StuffDao {

    @Override
    public List<Stuff> getAllStuff() {
        return getHQLResult("select Stuff.* from Stuff inner join OtherStuff on Stuff.Id = OtherStuff.Id", null);
    }
}

你不能那样做。 Spring 缓存 "method execution" - 当你调用方法时 Spring 检查缓存中是否存在键和 returns 相应的值,否则调用方法,数据是从数据库中提取,添加到缓存并返回。当您将一些 table 与其他 table 连接时,这会在数据库中发生。

您无法使用 Spring 缓存在数据库中缓存 table。仅从方法返回值。

如果你想在内存中缓存一些数据库table,有些数据库提供了这样的功能,但你必须在数据库中而不是在服务器上这样做。