我正在使用Spring JPA来查询JPA对象列表(例如B),该列表与具有延迟获取功能的另一个对象(例如A)有关系。 JPQL基于延迟加载的对象进行过滤将引发异常
原因:org.hibernate.LazyInitializationException:无法初始化代理-没有会话异常。
如何解决此问题?
我尝试使用JOIN
,FETCH
,LEFT JOIN
和@EntityGraph
属性。我没有得到预期的结果。
@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
...
}
}
我希望findBsByParent方法应该返回所有具有给定parentId的B。不幸的是,我无法在这里使用native query
。
答案 0 :(得分:0)
在您的application.properties
文件中添加以下属性:
hibernate.enable_lazy_load_no_trans = true