如何在JPA Hibernate中对外部列进行排序?

时间:2016-03-17 13:40:36

标签: java spring hibernate jpa

我有一个名为Project的实体,其外部Department实体具有name字段(见下文):

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

  ...
}

然后,在我的ProjectService课程中,我有一个方法:

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

有没有办法使用这种方法按Department排序name?如果有,怎么样?如果不是,最好的方法是什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

<强>解决:

我应该尝试过。它就像使用点(。)运算符引用字段一样简单。哇。

case DEPARTMENT_NAME:
       sort = new Sort(new Order(direction, "department.name"),
                       new Order(Direction.DESC, "created"));