Hibernate org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:

前端 未结 3 1564
失恋的感觉
失恋的感觉 2021-01-05 11:25

I have the below mentioned Entity classes, when I execute my application I am getting the following exception. Some of the other similar questions didn\'t solve the problem.

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 12:04

    If you would like to continue using FetchType.LAZY but need access to the lazily loaded attributes for some queries, a portable solution would be to access the field and perform an operation on it while still within a transaction/session. I mention portability because AFAIK Hibernate offers at least one different approach to explicitly trigger loading that is not part of the JPA spec.

    Adapting your code, this could look like this:

    public List findAllEmployees() {
      List employees = getEntityManager().createNamedQuery("Emp.findAllEmployees",
        Emp.class).getResultList();
    
      //trigger loading of attributes
      for(Emp emp: employees){
        emp.getDeptNo().getEmpDetNo().size();
      }
      return employees;
    }
    

    EDIT: Another portable alternative would be to use fetch joins in the query. Your Emp.findAllEmployees query could look like this:

    SELECT e FROM Emp e JOIN FETCH e.dept.empDetno
    

    Make it a left join if you have Emps without departments and departments without empDetNo

提交回复
热议问题