I have the following (horse-fuscated) function with the appropriate repositories wired in the class, that access two entities to build a response object:
public HorseTypeResponse getHorseType(Long horseId) {
Optional<HorseJpa> horse = horseRepository.findById(horseId);
if (horse.isPresent()) {
Integer horseTypeId = horse.get().getHorseTypeId();
String horseType = "";
Optional<HorseTypeJpa> horseType = horseTypeRepository
.findById(horseTypeId);
if(horseType.isPresent()){
horseTypeName = horseType.get().getName();
}
return HorseTypeResponse.builder()
.horseId(horseId)
.horseTypeId(horseTypeId)
.horseTypeName(horseTypeName)
.build();
}
throw new NotFoundExecption("Horse " + horseId + " does not have a type.");
}
But when I try and call this function from the controller, I get the following response:
could not initialize proxy [...domain.entities.main.HorseTypeJpa#3] - no Session","throwable_class":"LazyInitializationException
It is worth noting that the following is set on this project:
jpa.open-in-view: false
While a relationship between HorseJpa and HorseTypeJpa exists, so such relationship is configured with any annotations or types and the objects are as simple as:
@Entity
public class HorseJpa {
@Id
@Column(name = "ID")
private Long HorseId;
@Column(name = "TypeId")
private Integer horseTypeId;
}
and
@Entity
public class HorseTypeJpa {
@Id
@Column(name = "ID")
private Integer horseTypeId;
@Column(name = "Name")
private String name;
}
This error only started appearing after jpa.open-in-view: false was set on the project.
Initially horseTypeRepository used getById which is already marked as deprecated which only returns a proxy of the entity rather than the enity, so I thought this was it and reworked it to use findById
In the end this was resolved by creating a HorseTypeView and using a native query and a LEFT JOIN to produce the entity. But I do not know why the tow select's of non linked entities resulted in the exception.
Why does the LazyInitializationException still get thrown for for two DB reads, that are not forcefully linked in any way, and which both gets mapped to their corresponding field on the response object?
This question is NOT how to resolve the LazyInitializationException