private Set<Employee> assignees = new HashSet<>();



 public Set<Employee> getAssignees() {
            return assignees;
        }

        public void setAssignees(Set<Employee> assignees) {
            this.assignees = assignees;
        }


我在下面的代码中使用了上述方法,并且在运行该代码时遇到了此异常。

 `Resolved exception caused by Handler execution: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:`


它来自执行
 agendaInfo.setAssignees(item.getAssignees());行。
为什么会得到这种例外?

@Override
        public List<AgendaContentDTO> getAgendasByMeetingId(Long meetingId) {

            List<Agenda_content> agendas = extendedAgendaContentRepository.getAgendasByMeetingId(meetingId);
            List<AgendaContentDTO> agendaDTOS = new ArrayList<>();

            Long currentUser = utils.getCurrentEmployeeId();

            for (Agenda_content item: agendas){

                AgendaContentDTO agendaInfo = new AgendaContentDTO();

                agendaInfo.setId(item.getId());
                agendaInfo.setTitle(item.getTitle());
                agendaInfo.setContent(item.getContent());
                agendaInfo.setMeetingId(item.getMeeting().getId());
                agendaInfo.setMeetingMeetingName(item.getMeeting().getMeetingName());
                agendaInfo.setAssignees(item.getAssignees());

              agendaDTOS.add(agendaInfo);
            }
            return agendaDTOS;
        }

public interface ExtendedAgendaContentRepository extends Agenda_contentRepository {

    @Query("select distinct e.meeting from Agenda_content e join e.assignees a where a.id =:assigneeId")
    public List<Meeting> getMeetingsAssignedToMe(@Param("assigneeId") long assigneeId);

    @Query("select distinct e from Agenda_content e where e.meeting.id =:meetingId")
    public List<Agenda_content> getAgendasByMeetingId(@Param("meetingId") long meetingId);


}

最佳答案

集合是在休眠状态下延迟加载的,因此,当您从getAgendasByMeetingId加载数据时,休眠状态会加载Agenda_content列表,但不存在collection(Assignees)。

LazyInitializationException由于您的事务中没有事务(未打开会话)而无法使用
 public List<AgendaContentDTO> getAgendasByMeetingId(Long meetingId) {代码

如果您使用的是spring,请使用@Transaction标记您的方法
或在休眠状态下,您需要打开一个会话

或者,您可以在集合上使用fetchType = FetchType.EAGER,以便在加载Agenda_content时休眠加载所有getAssignees。

10-01 05:25