我有一个 LazyInitializationException 问题,我不知道如何解决它。for (Long id : employeeIds) { List<ProjectEmployee> projectEmployeeList = projectEmployeeService.findProjectEmployeesWithinDates(id, startDate, endDate); // if no data, then continue with next employee if (projectEmployeeList.isEmpty()) { continue; } gridCreated = true; Employee employee = projectEmployeeList.get(0).getEmployee(); Label titleLabel = new Label(employee.getPerson().getSurname() + " " + employee.getPerson().getName() + " [" + employee.getRole().getHumanizedRole() + "]"); titleLabel.setStyleName("header-bold"); ProjectEmployeePanel projectEmployeePanel = new ProjectEmployeePanel(id, startDate, endDate); gridPanelsLayout.addComponents(titleLabel, projectEmployeePanel); }在问题出现之前,当我打电话给 .getperson=null 但我修复了调用 findProjectEmployeesWithinDates 要求那里接人的问题。但是当我调用“findProjectEmployeesWithinDates”时出现异常。代码 findProjectEmployeesWithinDates: public List<ProjectEmployee> findProjectEmployeesWithinDates(Long employeeId, LocalDate startDate, LocalDate endDate) { List<Long> list = new ArrayList<>(); list.add(employeeId); List<ProjectEmployee> listProjectEmployees = projectEmployeeRepository.findProjectEmployeesWithinDates(list, LocaleUtils.getDateFromLocalDate(startDate, LocaleUtils.APPLICATION_DEFAULT_ZONE_ID), LocaleUtils.getDateFromLocalDate(endDate, LocaleUtils.APPLICATION_DEFAULT_ZONE_ID)); for (ProjectEmployee pe : listProjectEmployees) { Hibernate.initialize(pe.getEmployee()); Hibernate.initialize(pe.getEmployee().getPerson()); } return listProjectEmployees;}所以使用 debbug 我看到了: Hibernate.initialize(pe.getEmployee()); ----line 105Hibernate.initialize(pe.getEmployee().getPerson()); ---line 106它位于 findProjectEmployeesWithinDates 中 for 循环的第一行,但不在第二行,这就是发生异常的地方。
2 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
我会推荐以下方法之一:
1)在您的存储库方法findProjectEmployeesWithinDates中,您可以执行
for (ProjectEmployee pe : listProjectEmployees)
{
pe.getEmployee().getPerson();
}
所以它会在会话打开时初始化对象
2)您可以使用查询获取数据
SELECT * FROM ProjectEmployee pe JOIN FETCH pe.employee e JOIN FETCH e.person
这样,Hibernates 将自动使用员工和人员对象填充执行结果
慕雪6442864
TA贡献1812条经验 获得超5个赞
当您调用 projectEmployeeRepository.findProjectEmployeesWithinDates 方法时,它会返回 List。此时您的休眠会话已经关闭。
因此,当读取 ProjectEmployee 对象时,您只能访问那些特定于对象的变量而不是特定于对象的子对象,因为您正在为子对象使用延迟初始化。
因此,解决方法是保持您的休眠会话打开或使用急切获取或使用包装类对象将值从 ProjectEmployee 类传输到 projectEmployeeRepository.findProjectEmployeesWithinDates 方法中的 ProjectEmployeeWrapper,然后返回 ProjectEmployeeWrapper 对象的列表
添加回答
举报
0/150
提交
取消