We have been developing a web site for about a year now, using Spring 4, Hibernate, repositories and JPA. We use the OpenEntityManagerInViewFilter to keep sessions open when retrieving data via endpoints, but recently have been working with scheduled actions and are now running into problems.
We have one method in one class with a @Scheduled annotation, and another method in another class with a @Transactional annotation. The calling method finds data on the file system and passes it to the second class/method.
Here's a simplified version of the code:
<code>
// metadataRepository
@Transactional
public Metadata findOneById(String uuid);
@Transactional
public void processQueueMessages(Map<String, MessageAttributeValue> attributes ) throws IOException{
Metadata metadata = null;
try{
metadata = metadataRepository.findOneById(uuid);
// REST call to get list of locations
GeotaggerList locationList = response.getResult();
// this call just maps fields, no database interaction
Map<String, GeoLocation> locationNameMap = metadataService.getKwebLocations(locationList, null);
for (Map.Entry<String, GeoLocation> entry : locationNameMap.entrySet()){
entry.getValue().setMetadata(metadata);
metadata.getGeoLocations().add(entry.getValue()); //fails
}
metadataService.save(metadata, username);
}
} catch (Exception e){
e.printStackTrace();
return;
}
</code>
The method/class that calls processQueueMessages has a @Scheduled annotation. I tried adding a @Transactional annotation on the caller, to no avail.
I've tried a few variants of placing the annotations, but always get this error: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: .domain.Metadata.geoLocations, could not initialize proxy - no Session
I can't do an eager fetch in the definition of the Metadata domain object because it's used a lot of places where we don't want eager loading.
I'm open to suggestions.