【发布时间】:2018-01-23 19:37:16
【问题描述】:
我正在使用 Spring Boot 1.5.9.RELEASE 并且我正在使用 spring @Cacheable
我想要完成的是在应用程序启动时缓存国家/地区查询,如下所示:
public interface CountryRepository extends JpaRepository<Country, BigInteger> {
@Cacheable(cacheNames = Constants.CACHE_NAME_ALL_COUNTRIES)
List<Country> findAll();
}
并在启动时按如下方式调用它:
@Component
public class StartUpInit {
@Autowired
private CountryRepository countryRepository;
@EventListener
public void onApplicationReady(ApplicationReadyEvent ready) {
List<Country> list = countryRepository.findAll();
}
}
显而易见的是,随后对 findAll 的调用将从缓存中加载数据,但我想要做的是如下所示:
@Entity
@Table(name = "PROJECT")
public class Project {
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COUNTRY_ID")
private Country country;
@Cacheable(cacheNames = Constants.CACHE_NAME_ALL_COUNTRIES)
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
当我试图从项目对象中获取国家时,我希望从缓存而不是数据库中检索国家;我知道我可以缓存包含所有数据的整个项目对象,但我不想这样做,我只想从缓存中获取其中的查找
【问题讨论】:
-
@Cacheable用于缓存方法调用的结果。它不会缓存单个实体以供以后在 ID 或其他内容上检索。而是使用持久性提供程序的二级缓存。
标签: java spring spring-boot caching spring-cache