In my Configuration class I need to run a method as a cronjob. So I created a method by using the @Scheduled annotation.
@Scheduled(initialDelay = 10 * 1000, fixedRate = 1000 * 1000)
public void ThemeUpdate() {
List<ThemeIndex> indices = getServices();
...
}
The ThemeUpdate() method is now running in its own thread and I will lose my transaction. So I created another method by using the @Transactional annotation.
@Transactional
public List<ThemeIndex> getServices() {
List<Service> services = serviceRepository.findServices();
Section section = services.get(0).getSections().iterator().next();
return null;
}
I get my List<Service> services from my serviceRepository. But if I want to access a Section which is an Entity fetched by lazy loading why do I get a 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
What do I miss here?
EDIT:
Scheduled:
@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())) {
...
}