0
votes

I'm using Spring JPA to query a list of JPA objects (say B) which has a relation to another Object (say A) with lazy fetch. JPQL to filter based on the lazy-loaded object throws an exception
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session exception.
How to solve this?

I tried using JOIN, FETCH, LEFT JOIN and @EntityGraph attributes. I couldn't get the expected result.

@Entity
public class B {
    ...
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "A_Id", referencedColumnName="id", nullable = false)
    private Parent parent;
    ...
}

public interface BRepository extends PagingAndSortingRepository<B, Integer> {

    ...
    @Query("SELECT b FROM B b join fetch b.parent p where p.id = :parentId")
    List<B> findBsByParent(@Param("parentId") int parentId);
    ...
}

@Service
public class MyService {
   @Autowired
   private BRepository bRepository;

   public void workFunc(int parentId) {
      List<B> bList = bRepository.findBsByParent(parentId);
      ...
      // do certain ops with bList and other stuff too
      ...
   }
}

I expect findBsByParent method should return all B's that has given parentId. Unfortunately, I wouldn't be able to use native query here.

1
how did you map Parent? - Stefan Golubović
Can we please show the context where this is done? - akortex
I've added the service info as well now. - sheikhisham
Can you provide full stacktrace and Parent class implementation? - Lemmy

1 Answers

0
votes

Add following property in your application.properties file:

hibernate.enable_lazy_load_no_trans = true