【问题标题】:Cache lookups on application startup and reuse it in Hibernate entity在应用程序启动时缓存查找并在 Hibernate 实体中重用它
【发布时间】: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


【解决方案1】:

@Cacheable 注释需要放在 Spring Beans 上,而不是实体上,但我认为它也不适用于存储库。您的配置中还需要@EnableCaching。这是一个很好的教程: Caching Data with Spring 显示了一个例子。所以基本上你会创建类似CountryService 的东西,它由你的CountryRepository 支持,并且在服务上有注释。

编辑: 无法让该注释在实体中工作,@Cacheable 必须在 Spring Bean 中。你可以做的只是在项目中保存国家的ID,并使用具有缓存的CountryService来检索国家,这将阻止你每次检索Project时访问国家表,但如果你问题只是如何让@Cacheable 在不可能的实体中工作。

【讨论】:

  • ,我的缓存已启用,它在存储库中运行良好,我的问题很明确,我希望它使其在实体中运行
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2015-07-19
  • 2020-04-23
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
相关资源
最近更新 更多