How do I sort a foreign column in JPA Hibernate?

Viewed 1759

I have an entity named Project with a foreign Department entity that has a name field (See below):

@Entity
@Table(name = "project")
public class Project 
{
  @GeneratedValue(generator = "system-uuid")
  @GenericGenerator(name = "system-uuid", strategy = "uuid2")
  @Type(type = "pg-uuid")
  @Id
  @Column(name = "project_id")
  private UUID id;

  @Column(nullable = false)
  private String name;

  @Column(nullable = true, unique = false)
  private String description;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "department_id", nullable = false)
  private Department department;

  ...
}

Then, in my ProjectService class I have a method:

    public Page<Project> findByFilterSort(final ProjectSearchDTO dto,
                                          ProjectSortBy sortBy,
                                          Direction direction,
                                          int pageNumber,
                                          int pageSize)
    {
        BooleanBuilder builder = createFilter(dto);

        Sort sort;
        switch (sortBy)
        {
            case NAME:
                sort = new Sort(new Order(direction, "name"),
                                new Order(Direction.DESC, "created"));
                break;
            case DEPARTMENT_NAME:
                ???

            ...
        }

        PageRequest request = new PageRequest(pageNumber-1, pageSize, sort);

        return projectRepository.findAll(builder, request);
    }

Is there a way to sort the Department by name using this approach? If yes, how? If no, what is the best way?

Thanks in advance.

2 Answers

UPDATE
In newest version of spring data (2.5.5) new Sort() has private access, should use:

 Sort.by(new Order(direction, "department.name"))
Related