spring-data-jpa 使用嵌套对象的属性对Spring Data 进行JPA排序

pvabu6sv  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(281)

请考虑以下结构:

public class Survey {
  @ManyToOne
  @JoinColumn(name = "team_id")
  private Team team;
}

public class Team {
  private String teamName;
}

我已经创建了一个REST端点来获取所有调查。它还提供分页和排序功能:

@GetMapping("/all")
  public ResponseEntity<SurveyListViewResponse> getAllSurveys(
      @RequestParam(required = false) String userName,
      @RequestParam(required = false) String userEmail,
      @RequestParam(required = false) String teamName,
      @RequestParam(value = "quarter", required = false) String namedQuarter,
      @RequestParam(defaultValue = "id") String orderBy,
      @RequestParam(defaultValue = "DESC") Sort.Direction direction,
      @RequestParam(defaultValue = AppConstant.DEFAULT_PAGE) int page,
      @RequestParam(defaultValue = AppConstant.DEFAULT_PAGE_SIZE) int size,
      @RequestParam(required = false) SurveyStatus status) {

    Sort sort = Sort.by(direction, orderBy);
    Pageable paging = PageRequest.of(page, size, sort);

    SurveyListViewResponse surveyListViewResponse =
        surveyService.findAllSurveys(surveySpecification, paging);

    return ResponseEntity.status(HttpStatus.OK).body(surveyListViewResponse);
  }

因此,在接受orderBy的同时,还需要对嵌套对象中的属性进行排序,如teamNameuserNameuserEmail等。
将这些属性传递给Sort.by方法是不可能的。

nnt7mjpx

nnt7mjpx1#

为了实现这一点,我们可以像在查询DSL中接受参数一样传入参数。例如,如果我们想根据teamName对所有Surveys进行排序,我们只需将team_teamName作为属性传递给Sort.by方法,即Sort sort = Sort.by(Sort.Direction.ASC, "team_teamName");

相关问题