Spring与JPA结合时,如何解决懒加载no session or session was closed!!!
请注意,是懒加载的情况下...
如:
@Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @ManyToOne(cascade = { CascadeType.PERSIST }, optional = false, fetch = FetchType.LAZY) private Teacher banzhuren; @Entity public class Teacher { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = "banzhuren") private Set <Student> students = new HashSet <Student>();
直接使用EntityManager对象的时候并不会出错,如:
@Test public void testRead(){ Teacher teacher = manager.find(Teacher.class, 1); System.out.println(teacher.getId()); System.out.println(teacher.getStudents().size()); } @Test public void testRead2(){ Student student = manager.find(Student.class, 1); System.out.println(student.getId()); System.out.println(student.getBanzhuren().getId()); }
但是,在使用Spring后,封装EntityManager后,如:TeacherService中使用EntityManager,单独读取Teacher或Student正常,但是在读取Tacher后,读取Student,就会出现no session or session was closed的懒加载异常...
如果,不设置懒加载,几乎代码是没有什么问题的...为什么设置懒加载后,spring与JPA集合使用就出现这个异常...
这个异常的原因,我的理解是spring上的一个不足...
因为,如果是开发的web项目.这个问题,可以在web.xml中增加配置:
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
当session closed!而需要session的时候,就会自动获取session...从而解决以上的问题....而在不是web项目的开发时候(或者单元测试的时候),这个问题的解决办法,尚未找到...请高人留言...