Spring Data JPA实现多条件排序

先说下Sort类常用的几个构造方法

1.

public Sort(Order... orders) {
   this(Arrays.asList(orders));
}

2.

public Sort(List<Order> orders) {

   Assert.notNull(orders, "Orders must not be null!");

   this.orders = Collections.unmodifiableList(orders);
}

3.

public Sort(String... properties) {
   this(DEFAULT_DIRECTION, properties);
}

4.

public Sort(Direction direction, String... properties) {
   this(direction, properties == null ? new ArrayList<>() : Arrays.asList(properties));
}

5.

public Sort(Direction direction, List<String> properties) {

   if (properties == null || properties.isEmpty()) {
      throw new IllegalArgumentException("You have to provide at least one property to sort by!");
   }

   this.orders = new ArrayList<>(properties.size());

   for (String property : properties) {
      this.orders.add(new Order(direction, property));
   }
}

注:Direction是用来标识列属性升序还是降序排序的

    properties即为列属性

在上面5个方法中,4,5方法只能实现一种排序方向。

                               3方法输入列名,按照默认的排序方式(ASC)

              在介绍下Order的构造方法:

  public Order (Direction direction,String properties);    --------Order维护一个Direction和一个列属性

   所以,采用的方法;

@RequestMapping("/sort")
public List<Person> sort(){
    List<Sort.Order> orders=new ArrayList<>();
    orders.add(new Sort.Order(Sort.Direction.DESC,"age"));     ---age降序
    orders.add(new Sort.Order(Sort.Direction.ASC,"name"));     ---naem升序
    return personRepository.findAll(Sort.by(orders));
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值