• 79. could not initialize proxy


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

           SpringJPA结合时,如何解决懒加载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

  • 相关阅读:
    CentOS初步学习记录(五)用户和用户组
    CentOS初步学习记录(四)curl文件传输和grep文本搜索
    微信公众号推文svg点击交互的方法
    layaair写动画的方法 用时间轴最方便
    spring boot 整合Elasticsearch
    java spring boot 拦截器 实现未登录用户不能登录
    java win 安装 activemq教程
    java spring boot Swagger2 构建api文档
    java spring boot @bean的用法
    java spring boot 写入日志
  • 原文地址:https://www.cnblogs.com/hehehaha/p/6147059.html
Copyright © 2020-2023  润新知