org.hibernate.LazyInitializationException: could not initialize proxy 解决方案(JPA)

错误信息:org.hibernate.LazyInitializationException: could not initialize proxy

原因:在根据 Id 获取对象中使用了 getOne() 方法

解决方案:

1. 如果使用 JPA 时使用了 getOne() 方法就会报这个懒加载异常

非得想使用 getOne() 方法的话,可以在 application.properties 配置文件中添加(不推荐)

  spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

2. 第二种方案,使用 jpa 的 findById() 方法替代 getOne() 方法,这样就不会报异常了(推荐)

Optional<ApplicationEntity> optional = applicationRepository.findById(id);
if (optional.isPresent()) {
appInfo = optional.get();
}
原文地址:https://www.cnblogs.com/dingjiaoyang/p/15190164.html