Alex Rivera | Logout

Hibernate: org.hibernate.LazyInitializationException: could not initialize proxy - no Session

Asked 2013-01-26T22:17:19.103
15

Have following query to the database:

        Session session = EmployeesDAO.getSessionFactory().getCurrentSession();
        List<Employee> employees = new ArrayList<Employee>();
        try {
            session.beginTransaction();
            String hqlQuery = "from Employee emp "
                    + "left join fetch emp.employeesOffices employeesOffice "
                    + "left join fetch employeesOffice.office employeesOfficeOffice "
                    + "left join fetch employeesOfficeOffice.company "
                    + "left join fetch emp.address empAddress "
                    + "left join fetch empAddress.city empAddressCity "
                    + "left join fetch empAddressCity.country";
            Query empQuery = session.createQuery(hqlQuery);
            empQuery.setMaxResults(maxResult);
            employees = (List<Employee>) empQuery.list();
            session.getTransaction().commit();

        } catch (HibernateException e) {
            session.getTransaction().rollback();
            e.printStackTrace();
        }

While fetching employee.address.street, employee.address.houseNumber or employee.address.city it fails with the exception:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at com.employees.model.Address_$$_javassist_6.getCity(Address_$$_javassist_6.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
  
Edit
Report

1 Answer

9

Has nothing to do with the mapping. When you provide for lazy loading on an object, you accept a responsibility that has bewitched the ORM world for a decade: that the session you loaded the object with will be the same one as the session that is present when the lazy requests are issued.

In your case, it looks like the session is completely gone.

You have to have some means of either maintaining the session (which often leads to a need for conversation scope, which would mean either Seam or CDI (in EE 6)) or you have to resync your object with the new session that you have (usually by looking it up again).

answered 2013-01-26T22:22:20.807

Your Answer