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

【原创文章,转载请注明出处】

       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已经关闭了,我们支持在Spring MVC中需要配置一个OpenEntityManagerInViewFilter过滤器,Spring针对Hibernate的非JPA实现用的是OpenSessionInViewFilter,那么在Spring Boot中怎么支持呢?

特别特别的简单,只需要在application.properties中加入如下配置:

spring.jpa.open-in-view=true

这么一个配置即可支持,默认这个值就为true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值