Running into an issue with LazyInitialization that I am at a loss for how to resolve.
Repository Link: GitHub - ahabib1980/archival
Context: I am writing a module that archives a subset of patient data (specifically encounters, encounter providers, obs) by moving them to a different set of tables with the intent to reduce load on a large database for one of our clients. I have structured this as follows:
- User selects a set of patients to archive
- The module goes through the list of patients, archiving all encounters/enc providers/obs that don’t have other dependencies. The archival of each encounter is a transaction i.e. the encounter, linked encounter providers, and obs are either all archived or the entire encounter is skipped (i.e. transaction rolled back). A patient’s data can be partially archived i.e. it’s okay if some encounters are archived and others aren’t.
- This is done via a controller receiving a list of patients from a JSP page, extracting their encounters, and iterating through the list of encounters, invoking a service method (ArchivalService() -> archiveEnounter() ) to archive each encounter. In line with what I understand is a Spring recommendation, I have annotated archiveEncounter() as @Transactional in the concrete class (ArchivalServiceImpl) for my service.
Problem I am facing: When the encounters can all be archived successfully, everything works fine. However, in the instance where I have, say, one patient with two encounters and for some reason (e.g. a dependency on Order) the first encounter can’t be archived, the first transaction appears to be rolling back just fine, but the attempt to archive the next encounter fails with a LazyInitializationException (LazyInitializationException - Pastebin) when accessing the EncounterProviders for the Encounter in question. I’m not sure I understand why one failed/rolled-back transaction is terminating the entire session. I’m probably missing either something really obvious or really arcane around Transaction Management in Spring/OpenMRS. Any and all help appreciated.