i am using springboot 1.5.9.RELEASE and i am using spring @Cacheable
and what i am trying to accomplish is to cache a country lookup on application startup as follows:
public interface CountryRepository extends JpaRepository<Country, BigInteger> {
@Cacheable(cacheNames = Constants.CACHE_NAME_ALL_COUNTRIES)
List<Country> findAll();
}
and call it on startup as follows:
@Component
public class StartUpInit {
@Autowired
private CountryRepository countryRepository;
@EventListener
public void onApplicationReady(ApplicationReadyEvent ready) {
List<Country> list = countryRepository.findAll();
}
}
the obvious thing is that subsequent calls to findAll will load the data from the cache, but what i am trying to do is something like the following :
@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;
}
}
i want when trying to get country from project object the country to be retrieved from the cache instead of database,i know that i can cache the whole project object with all data in it but i don't want to do that i want only to get the lookup inside it from the cache , please advise how to do that.
答案 0 :(得分:0)
@Cacheable
注释需要放在Spring Beans上,而不是实体上,但我也不认为它适用于存储库。您的配置中还需要@EnableCaching
。这是一个很好的教程:
Caching Data with Spring显示了一个例子。所以基本上你会创建一个由CountryService
支持的CountryRepository
,并且在服务上有注释。
修改:
无法在实体中使用该注释,@Cacheable
必须位于Spring Bean中。您可以做的只是在项目中保存国家/地区的ID,并使用具有缓存的CountryService
来检索国家/地区,这将阻止您每次检索Project
时访问国家/地区表,但如果你的问题只是如何让@Cacheable
在一个不可能的实体中工作。