spring-boot 完美解決:could not initialize proxy
Spring與JPA結合時,如何解決懶載入no session or session was closed!!!
實際上Spring Boot是預設是開啟支援session view filter的,所以大家正常應該是不會發現有這個問題的,但是還是有人提出了,好吧,如果真的碰到的話,那麼可以按照如下嘗試解決下。
我們先看看有這麼幾個類(省略一些程式碼,只提供核心的):
Teacher:
@Entity
public class Teacher {
@Id @GeneratedValue
private long id;
private String teaName
}
Student:
@Entity
public class Student {
@Id@GeneratedValue
private long id;
private String stuName;
@ManyToOne(fetch = FetchType.LAZY)
private Teacher classTeacher;
}
StudentRepository:
public interface StudentRepository extends CrudRepository<Student,Long>{
}
訪問控制器:
@RequestMapping("/hello")
public String hello(Map<String,Object> map){
map.put("student",studentRepository.findOne(1L));
return "/hello";
}
訪問/hello那麼如果出現如下異常資訊:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
那麼可以這是由於我們使用懶載入載入資料的方法,當我們要獲取的資料的時候,但是session已經關閉了,我們支援在Spring MVC中需要配置一個OpenEntityManagerInViewFilter 過濾器,Spring針對Hibernate的非JPA實現用的是OpenSessionInViewFilter,那麼在Spring Boot中怎麼支援呢?
特別特別的簡單,只需要在application.properties中加入如下配置:
spring.jpa.open-in-view=true
這麼一個配置即可支援,預設這個值就為true
原文章url:http://412887952-qq-com.iteye.com/blog/2315230