Spring Data Specification中Eager fetching失效问题求助
Spring Data Specification中Eager fetching失效问题求助
各位大佬,我最近在使用Spring Data JPA的Specification做动态条件查询时碰到了个棘手的问题,想请教下大家:
我在User实体类里给关联的orders字段配置了立即加载(FetchType.EAGER),代码如下:
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private List<Order> orders;
然后Service层的查询逻辑用Specification来构建动态查询条件,具体代码是这样的:
@Override public List<UserResponseDto> find(FindUserRequestDto userRequestDto, Pageable pageable) { Specification<User> specification = buildSpecification(userRequestDto); List<User> users = repository.findAll(specification, pageable); List<UserResponseDto> userDtos = users.stream() .map(userMapper::toResponseDto) .toList(); return userDtos; }
奇怪的是,当我直接调用repository.findAll(pageable)的时候,orders字段能正常被立即加载出来,但一用Specification构建查询条件后,orders就变成了懒加载的代理对象,后面在Mapper里访问orders的属性时直接抛出了LazyInitializationException。
我自己排查了好一会儿也没找到根因,有没有大佬遇到过类似的情况?求帮忙分析下问题出在哪,或者该怎么解决呀?
内容来源于stack exchange
相关产品推荐
相关产品推荐

