Home > other >  Spring Data JPA Sort with Nested Object's Property
Spring Data JPA Sort with Nested Object's Property

Time:08-13

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. 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.

Passing these properties to the Sort.by method is not possible.

CodePudding user response:

To achieve this, we can pass in the parameter the same way we accept a parameter in 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 i.e. Sort sort = Sort.by(Sort.Direction.ASC, "team_teamName");

  • Related