简体   繁体   English

Spring 数据 JPA 使用嵌套对象的属性排序

[英]Spring Data JPA Sort with Nested Object's Property

Consider the following structure:考虑以下结构:

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

public class Team {
  private String teamName;
}

I've created a REST endpoint to get all surveys.我创建了一个 REST 端点来获取所有调查。 It also provides paging and sorting capabilities:它还提供分页和排序功能:

  @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);
  }

So while accepting orderBy , there's a requirement to sort with properties within the nested objects like teamName , userName , userEmail , etc.因此,在接受orderBy ,需要使用嵌套对象中的属性进行排序,例如teamNameuserNameuserEmail等。

Passing these properties to the Sort.by method is not possible.无法将这些属性传递给Sort.by方法。

To achieve this, we can pass in the parameter the same way we accept a parameter in Query DSL.为此,我们可以像在 Query DSL 中接受参数一样传入参数。 So for example, if we want to sort all the Surveys with respect to teamName , we have to simply pass team_teamName as property to Sort.by method ie Sort sort = Sort.by(Sort.Direction.ASC, "team_teamName");例如,如果我们想对所有关于teamNameSurveys进行排序,我们必须简单地将team_teamName作为属性传递给Sort.by方法,即Sort sort = Sort.by(Sort.Direction.ASC, "team_teamName");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM