Search code examples
javahibernatejpaspring-data-jpaspring-transactions

Prevent no session fails in case of passing JPA repo methods


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.LAZYto 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?


Solution

  • 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:

    • Eagerly fetch all the required dependencies while the session is still opened (join fetch)
    • Use Hibernate.initialize(x.getY()); inside of the transactional context
    • Call size method on the depenedent colletions to initialze them x.getY().size.