zoukankan      html  css  js  c++  java
  • spring data for jpa 实现多条件排序

    例如需要实现一个形如下面的sql:
     
    select * from table where a='a' and b='b' order by c asc,d desc;
     
    就是根据两个条件进行排序。
     
    在spring data for jpa 中,存在一个pageable接口,是对查询分页的一个利器。
    pageable实现类的构造方法中有个Sort参数,可以按照列属性进行排序。通过查看Sort类的构造方法,我们对Sort这个类进行一下分析,Sort类中存在一下几个构造方法:
     
    1.public Sort(Order... orders);
     
    2.public Sort(List<Order> orders);
     
    3.public Sort(String... properties);
     
    4.public Sort(Direction direction, String... properties);
     
    5.public Sort(Direction direction, List<String> properties);
     
    大概这几种构造方法,其中Direction 是用来标识按照列属性升序还是降序排序的。
     
    properties即为列属性。
     
    因为我们要排列的两个属性升序和降序都存在,4、5方法由于只能够实用一种排序方向,所以不能采用。
     
    方法3只是输入列属性,按照默认的排序方式(ASC),因此也不能满足要求。
     
    接下来我们看构造方法1和2,性质相同,主要是Order类的用途是怎样的。
     
    看一下Order类的构造方法:
     
    public Order(Direction direction, String property);
     
    可以看到一个Order维护一个Direction 和一个列属性,正式我们所要的。
     
    所以采用如下的方法:
     
    List< Order> orders=new ArrayList< Order>();
    orders.add( new Order(Direction. ASC, "c"));
    orders.add( new Order(Direction. DESC, "d"));
    Pageable pageable= new PageRequest(pageNumber, pageSize, new Sort(orders));
    jpaRepo.findByAAndB(a,b,pageable);
  • 相关阅读:
    我藏在你的心里,你却不愿意寻找# BUG躲猫猫
    阴间需求之跨端登录
    神奇的props
    map与filter:你先我先?
    阴间BUG之动态路由刷新几率回首页
    阴间BUG之动态路由添加失败
    我在eltable就变了个模样,请你不要再想我,想起我
    SCP打包部署方法
    indexOf 与 includes
    YACC和BISON学习心得
  • 原文地址:https://www.cnblogs.com/yanzhenxing/p/3083156.html
Copyright © 2011-2022 走看看