Hibernate - Avoiding LazyInitializationException - Detach Object From Proxy and Session

前端 未结 3 434
旧时难觅i
旧时难觅i 2020-12-03 23:44
MyObject myObject = repositoryHibernateImpl.getMyObjectFromDatabase();
//transaction is finished, and no, there is not an option to reopen it
ThirdPartyUtility.doStu         


        
3条回答
  •  伪装坚强ぢ
    2020-12-04 00:11

    check my solution.

    Minimal example:

    I do not load the property from the object but from the controller.
    Code:

    {..}
    
    MyProp prop = employeeController.getMyProp(employee);
    
    {..}
    

    This initiaqlizes the property via repository object and returns it.
    EmployeeController.java:

    public Set getMyProp(Employee employee) {
    
        if (this.employeeRepository.InitMyProp(employee)){
    
            return employee.getMyProp();
        }
    
        return null;
    }
    

    Repository get/open the session, reload employee object ! and initialize lazy loaded field
    EmployeeRepository.java:

    public boolean InitMyProp(Employee employee) {
    
        if (Hibernate.isInitialized(employee.getMyProp())){
            return true;
        }
    
        try {
            Session session = getSession();
    
            session.refresh(employee);
    
            Hibernate.initialize(employee.getMyProp());
    
        } catch (Exception ex) {
            return false;
        }
    
        return true;
    }
    
    private Session getSession(){
    
        if (session == null || !session.isConnected() || !session.isOpen()){
            session = HibernateUtil.getSessionFactory().getCurrentSession();
        }
        if (!session.getTransaction().isActive()) {
            session.beginTransaction();
        }
        return session;
    }
    

    I have in my solution a TableView with several thousand records and 2 further TableViews with details on the selected record in the first TableView.
    hope it helps.

提交回复
热议问题