Spring Data JPA LazyInitializationException问题

267 阅读1分钟

问题描述

Springboot 2.7.0版本,使用Spring Data JPA查询 repository继承

public interface ProjectRepository extends JpaRepository<Project, Long> {
}

使用repository默认方法,projectRepository.getReferenceById(),查询报错org.hibernate.LazyInitializationException: could not initialize proxy [xxx] - no Session at ...

解决方案

查看网上资料,大概包括4种解决办法,可参考 LazyInitializationException - What it is and the best way to fix it (thorben-janssen.com)

上面方案对于本文的场景都不吻合,查询Spring 官方文档获得答案Spring Data JPA - Reference Documentation

JpaRepository中有一个新的getById方法,它将取代现在不推荐使用的getOne。由于此方法返回引用,这将更改以前由查询派生实现的现有getById方法的行为。这反过来可能会导致在事务外部访问该引用的属性时出现意外的LazyLoadingException。为了避免这种情况,请将现有的getById方法重命名为getXyzById,其中Xyz是任意字符串。

getReferenceById方法同样是返回引用,所以解决办法是放弃使用该方法,在repository中重新定义需要的方法即可。