代码之家  ›  专栏  ›  技术社区  ›  Patrick

Spring数据在@Scheduled和@Transactional方法中延迟加载

  •  0
  • Patrick  · 技术社区  · 6 年前

    @Scheduled 注释。

    @Scheduled(initialDelay = 10 * 1000, fixedRate = 1000 * 1000)
    public void ThemeUpdate() {
        List<ThemeIndex> indices = getServices();
        ...
    }
    

    这个 ThemeUpdate() 方法现在正在自己的线程中运行,我将丢失事务。所以我用 @Transactional

    @Transactional
    public List<ThemeIndex> getServices() {
        List<Service> services = serviceRepository.findServices();
    
        Section section = services.get(0).getSections().iterator().next();
    
        return null;
    }
    

    List<Service> services serviceRepository Section 这是一个 Entity 偷懒的加载为什么我会得到一个 LazyInitializationException ?

    org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.myPorject.db.model.Service.sections, could not initialize proxy - no Session
    

    计划时间:

    @Scheduled(initialDelay = 10 * 1000, fixedRate = 10000 * 1000)
    @Transactional
    public void ThemeUpdate() {
        List<ThemeIndex> indices = themeUpdateServiceImpl.getIndices();
    }
    

    获取索引():

    @Override
    public List<ThemeIndex> getIndices() {
        return getIndices(serviceRepository
            .findServices());
    }
    
    @Override
    public List<ThemeIndex> getIndices(List<Service> services) {
        return themeIndexServiceImpl.getThemeIndexes(services);
    }
    

    getThemeIndexes():

    @Override
    public List<ThemeIndex> getThemeIndexes(List<Service> services) {
        List<ThemeIndex> themeIndexs = new ArrayList<>();
        for (Service s : services) {
            ThemeIndex themeIndex = getThemeIndex(s);
            if (themeIndex != null) {
                themeIndexs.add(themeIndex);
            }
        }
        return themeIndexs;
    }
    
    @Override
    public ThemeIndex getThemeIndex(Service service) {
        //SQL which is slow
        if (serviceRepository.isEpisService(service.getSvno())) {
            ...
        }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Simon Martinelli    6 年前

    您正在本地调用getServices(),因此本地方法调用没有事务代理。

    您应该在自己的组件中移动计划的方法,并用getServices()方法注入组件。