![](/img/trans.png)
[英]JOIN FETCH in spring-data-jpa does not fetch lazy associations
[英]Spring-data-jpa lazy loading in @Scheduled and @Transactional methods
在我的Configuration类中,我需要将一个方法作为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;
}
我从serviceRepository
获取List<Service> services
。 但是,如果我想访问作为通过延迟加载获取的Entity
的Section
,为什么会得到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())) {
...
}
您在本地调用getServices(),因此本地方法调用没有事务代理。
您应该将计划的方法移到其自己的组件中,并使用getServices()方法注入该组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.