美文网首页jpa
愉快的使用JPA进行数据查询(八)分页与排序

愉快的使用JPA进行数据查询(八)分页与排序

作者: 猪的尾巴 | 来源:发表于2017-07-28 00:31 被阅读344次

    对于开发网站的同学来说,分页与排序是十分蛋疼又不得不做的事情,spring-data-jpa当然也考虑到了这一点,打开JpaRepository的继承关系,发现有一个接口叫做PagingAndSortingRepository,顾名思义,这个接口提供了排序以及分页能力,内部仅有两个方法:

        /**
         * Returns all entities sorted by the given options.
         * 
         * @param sort
         * @return all entities sorted by the given options
         */
        Iterable<T> findAll(Sort sort);
    
        /**
         * Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object.
         * 
         * @param pageable
         * @return a page of entities
         */
        Page<T> findAll(Pageable pageable);
    

    虽然方法只有两个,但是通过Sort和Pageable这两个类的组合,已经能提供强大的分页排序功能。

    排序

    我们先对查询数据进行排序,以id倒序方式查询出学生。
    需要使用Iterable<T> findAll(Sort sort)方法,TeacherDao不需要做任何修改,先看一下Sort类的构造方法

    image.png

    总的来说,四个构造都调用了第二个方法,最终需要一个sort集合(也就是按照多个字段排序,sort有and方法直接加入sort),我们一般使用

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

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

    这两个构造方法。
    第一个传入需要用于排序的字段,采用默认的正序方法搜索,第二个指定排序方式,再传入需要排序的字段。我们编写业务代码:

      @RequestMapping("findStudentOrderByIdDesc")
      public List<Student> findStudentOrderByIdDesc(){
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        List<Student> students = studentDao.findAll(sort);
        return students;
      }
    

    在浏览器输入http://127.0.0.1:8080/findStudentOrderByIdDesc测试,得到结果:

    image.png

    是不是很简单?没有写一句SQL,我们可以在application.properties中输入spring.jpa.show-sql = true,来查看真实的SQL语句:

    Hibernate: select student0_.id as id1_2_, student0_.birthday as birthday2_2_, student0_.name as name3_2_, student0_.num as num4_2_, student0_.school_id as school_i5_2_, student0_.score_id as score_id6_2_ from student student0_ order by student0_.id desc
    

    当然,因为设置了主外键,并且未设置懒加载,jpa默认会把所有关联信息全部查出,这个就很可怕了,只能在数据量不是很大的时候使用。

    分页

    看一下Page<T> findAll(Pageable pageable)这个方法,重要的是Pageable ,Pageable是一个顶级接口,实现他的类如下:

    image.png

    其中QPageRequest类为QueryDSL框架设计,我们使用的是PageRequest。
    首先看构造方法:

    image.png

    大概可以猜测出都是什么用途:起始页,查询数量,以及排序。
    看到构造方法大概就知道怎么使用了,PageRequest也提供了更多人性化的方法,让你使用翻页就如同生活中看书一样简单:

    image.png

    开始编写业务代码:以id倒序,每次查出两个学生的基本信息

    
      @RequestMapping("findStudentOrderByIdDescWithPage/{page}")
      public List<Student> findStudentOrderByIdDescWithPage(@PathVariable("page") int page){
    
        Sort sort = new Sort(Sort.Direction.DESC, "id");
    
        PageRequest pageRequest = new PageRequest(page, 2, sort);
    
        List<Student> students = studentDao.findAll(pageRequest).getContent();
    
        return students;
      }
    

    在浏览器中输入http://127.0.0.1:8080/findStudentOrderByIdDescWithPage/x
    就可以得到结果。

    相关文章

      网友评论

        本文标题:愉快的使用JPA进行数据查询(八)分页与排序

        本文链接:https://www.haomeiwen.com/subject/umwtlxtx.html