zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Apache POI使用详解
    util.Date与sql.Date转换
    【转】javascript中not defined、undefined、null以及NaN的区别
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
    DC维护工具Repadmin
    Outlook 配置exchange 缓慢,无法通过
    Windows 服务器站点设置
    Exchange 挂载点权限问题
    Windwos 查看WWN Number
    Exchange 2016 多站点创建oab shadow 副本
  • 原文地址:https://www.cnblogs.com/hehehaha/p/6147059.html
Copyright © 2011-2022 走看看