您的位置:首页 > 编程语言 > Java开发

spring boot之解决懒加载session was closed问题

2017-08-01 16:25 615 查看
【原创文章,转载请注明出处】
       spring与JPA结合时,如何解决懒加载no
session or session was closed!!!
       实际上Spring Boot是默认是打开支持sessionview 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 Stringhello(Map<String,Object> map){

       map.put("student",studentRepository.findOne(1L));

       return "/hello";

    }
访问/hello那么如果出现如下异常信息:

org.hibernate.LazyInitializationException:
couldnot initialize proxy - no Session
       那么可以这是由于我们使用懒加载加载数据的方法,当我们要获取的数据的时候,但是session已经关闭了,我们支持在S
4000
pring MVC中需要配置一个OpenEntityManagerInViewFilter过滤器,Spring针对Hibernate的非JPA实现用的是OpenSessionInViewFilter,那么在Spring
Boot中怎么支持呢?
特别特别的简单,只需要在application.properties中加入如下配置:

spring.jpa.open-in-view=true
这么一个配置即可支持,默认这个值就为true。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐