What is the way to prevent the fail of no session using JPA repository in below case:
I have a class called X with relation @OneToMany
with fetch = FetchType.LAZY
to class Y. I create the whole method in a repository, then I pass it to the Service class, and after that, I pass it to the Controller.
While I want to get the object Y from class X by x.getY()
which is related via Lazy
fetchType I get an error (from Hibernate) called no session.
How can I prevent this error from happening?
You would have to enclose the x.getY()
call inside your @Transactional
method or to move the transaction boundaries higher up in the call hierarchy, so that invocation is included as well.
In general i would not move higher than the service so if you access that property for the first time in the Controller for example then other possible options would be to:
Hibernate.initialize(x.getY());
inside of the transactional contextsize
method on the depenedent colletions to initialze them x.getY().size
.