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.
Parent? - Stefan Golubović