• 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

  • 相关阅读:
    Windows Phone 在读取网络图片之前先显示默认图片
    ios开发 点击文本(TextField)输入的时候向上推以及输入之后恢复的动画
    51nod 1019 逆序数
    hdu 5455 Fang Fang
    51nod 1027 大数乘法
    51nod 1006 最长公共子序列Lcs
    51nod 1066 Bash游戏
    51nod 1069 Nim游戏
    51nod 1049 最大子段和
    51nod 1072 威佐夫游戏
  • 原文地址:https://www.cnblogs.com/hehehaha/p/6147059.html
Copyright © 2020-2023  润新知