【发布时间】:2018-08-31 12:03:50
【问题描述】:
在我的配置类中,我需要将方法作为 cronjob 运行。所以我使用@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();
}
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())) {
...
}
【问题讨论】:
标签: java hibernate spring-boot spring-data-jpa