javaspringhibernate

org.hibernate.LazyInitializationException (no session) despite annotation org.springframework.transaction.annotation.Transactional


The issue I have is that it seems that the Transaction of a method annotated with @Transactional seems not to be propagated in the nested methods because the required LazyLoading fails.

What it makes more strange is that the LazyLoading works in an integration test (via @SpringBootTest) but not in a deployed state (Spring Boot 3.3.2) when the HTTP request comes in.

The Entities are mapped as follows:

@Entity
public class VtBsoEntity {

  @Id
  private UUID id;

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "arriving_train_id", referencedColumnName = "id")
  private VtTrainEntity arrivingTrain;

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "leaving_train_id", referencedColumnName = "id")
  private VtTrainEntity leavingTrain;

  ...

}

@Entity
public class VtTrainEntity {
  
  @Id
  private UUID id;

  private Integer trainNo;

  ...
}

The REST-Controller looks as follows and is the entry point:

@RestController
public class TemplateMetadataController {

  private final TemplateMetadataService service;

  public ResponseEntity<List<GetTemplateMetadataDto>> findAllTemplates() {
    final List<TemplateMetadataModel> templates = service.findAll(); // point of failure (stack trace)
    ...
  }
...
}

The TemplateMetadataService is listed below:

@Service
public class TemplateMetadataService () {

  private final NumberCalculatorService numberCalculatorService;

  @Transactional(isolation = Isolation.READ_COMMITTED, readOnly = true)
  public List<TemplateMetadataModel> findAll() {
   ...
   return mapToModel()
  }

  private TemplateMetadataModel mapToModel() {
    ...
    numberCalculatorService.getNumberModel(templateMetadataEntity); // point of failure (stack trace)
  }

}

The NumberCalculatorService :

@Service
public class NumberCalculatorService {

  private final VtBsoEntityRepository vtBsoEntityRepository;

  public AggregateBsoNumberModel getNumberModel(TemplateMetadataEntity entity) {

    List<VtBsoEntity> bsoList = vtBsoEntityRepository
        .findAllByMuWoIdAndActive(entity.getId(), true);

   bsoList.getFirst().getArrivingTrain(); // LazyInitializationException, no session 

   ...

  }

}

Question: Why is the Persistence Context via the Transaction in NumberCalculatorService not present anymore?


Solution

  • Because the @Transactional annotation seems not to be prpopagated to the other @Service class I have solved it by an explicit join fetch Query in the @Repository class.