整合Spring Data JPA与Spring MVC: 分页和排序pageable

https://www.tianmaying.com/tutorial/spring-jpa-page-sort

Spring Data Jpa对于分页以及排序的查询也有着完美的支持,接下来,我们来学习如何通过Pageable来对数据库进行分页查询。

添加maven依赖

首先我们需要引入Jpa,数据库直接使用hsqldb内存数据库就可以了:

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.5.RELEASE</version>
    </parent>
    <groupId>tmy</groupId>
    <artifactId>demo.jpa.page</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>tmy-spring-jpa-page-demo</name>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</project>

继承PagingAndSortingRepository

Jpa的基本使用方法在如何使用Jpa访问关系型数据库已经介绍过,我们暂且跳过,这里我们直接来看接口BlogRepository的定义:

 

public interface BlogRepository extends PagingAndSortingRepository<Blog, Integer> {

    Page<Blog> findByDeletedFalse(Pageable pageable);

}

我们可以看到,BlogRepository定义了这样一个方法:Page<Blog> findByDeletedFalse(Pageable pageable);,我们主要关注它的参数以及返回值。

  • Pageable 是Spring Data库中定义的一个接口,该接口是所有分页相关信息的一个抽象,通过该接口,我们可以得到和分页相关所有信息(例如pageNumberpageSize等),这样,Jpa就能够通过pageable参数来得到一个带分页信息的Sql语句。
  • Page类也是Spring Data提供的一个接口,该接口表示一部分数据的集合以及其相关的下一部分数据、数据总数等相关信息,通过该接口,我们可以得到数据的总体信息(数据总数、总页数...)以及当前数据的信息(当前数据的集合、当前页数等)

Spring Data Jpa除了会通过命名规范帮助我们扩展Sql语句外,还会帮助我们处理类型为Pageable的参数,将pageable参数转换成为sql'语句中的条件,同时,还会帮助我们处理类型为Page的返回值,当发现返回值类型为Page,Spring Data Jpa将会把数据的整体信息、当前数据的信息,分页的信息都放入到返回值中。这样,我们就能够方便的进行个性化的分页查询。

Pageable只是一个抽象的接口,那么,家下来我们学习如何获得pageable对象。

通过参数生成Pageable对象

Pageable定义了很多方法,但其核心的信息只有两个:一是分页的信息(page、size),二是排序的信息。Spring Data Jpa提供了PageRequest的具体实现,Spring MVC提供了对Spring Data JPA非常好的支持,我们只提供分页以及排序信息即可:

 

@RequestMapping(value = "/params", method=RequestMethod.GET)
public Page<Blog> getEntryByParams(@RequestParam(value = "page", defaultValue = "0") Integer page,
        @RequestParam(value = "size", defaultValue = "15") Integer size) {
    Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = new PageRequest(page, size, sort);
    return blogRepository.findAll(pageable);
}

在这里,我们通过参数获得分页的信息,并通过Sort以及Direction告诉pageable需要通过id逆序排列。Spring MVC的介绍情移步这里:Spring MVC快速入门

这里可以看到,通过参数来得到一个pageable对象还是比较繁琐的,当查询的方法比较多的时候,会产生大量的重复代码。为了避免这种情况,Spring Data提供了直接生成pageable的方式。

直接获取Pageable对象

 

@RequestMapping(value = "", method=RequestMethod.GET)
public Page<Blog> getEntryByPageable(@PageableDefault(value = 15, sort = { "id" }, direction = Sort.Direction.DESC) 
    Pageable pageable) {
    return blogRepository.findAll(pageable);
}

我们可以看到,我们只需要在方法的参数中直接定义一个pageable类型的参数,当Spring发现这个参数时,Spring会自动的根据request的参数来组装该pageable对象,Spring支持的request参数如下:

  • page,第几页,从0开始,默认为第0页
  • size,每一页的大小,默认为20
  • sort,排序相关的信息,以property,property(,ASC|DESC)的方式组织,例如sort=firstname&sort=lastname,desc表示在按firstname正序排列基础上按lastname倒序排列

这样,我们就可以通过url的参数来进行多样化、个性化的查询,而不需要为每一种情况来写不同的方法了。

通过url来定制pageable很方便,但唯一的缺点是不太美观,因此我们需要为pageable设置一个默认配置,这样很多情况下我们都能够通过一个简洁的url来获取信息了。

Spring提供了@PageableDefault帮助我们个性化的设置pageable的默认配置。例如@PageableDefault(value = 15, sort = { "id" }, direction = Sort.Direction.DESC)表示默认情况下我们按照id倒序排列,每一页的大小为15。

返回结果

最后,让我们进入程序的根目录,运行命令mvn spring-boot:run将web应用启动起来,启动完成后,访问http://localhost:8080/页面,我们将看到如下结果:

 

{
  "content":[
    {"id":123,"title":"blog122","content":"this is blog content"},
    {"id":122,"title":"blog121","content":"this is blog content"},
    {"id":121,"title":"blog120","content":"this is blog content"},
    {"id":120,"title":"blog119","content":"this is blog content"},
    {"id":119,"title":"blog118","content":"this is blog content"},
    {"id":118,"title":"blog117","content":"this is blog content"},
    {"id":117,"title":"blog116","content":"this is blog content"},
    {"id":116,"title":"blog115","content":"this is blog content"},
    {"id":115,"title":"blog114","content":"this is blog content"},
    {"id":114,"title":"blog113","content":"this is blog content"},
    {"id":113,"title":"blog112","content":"this is blog content"},
    {"id":112,"title":"blog111","content":"this is blog content"},
    {"id":111,"title":"blog110","content":"this is blog content"},
    {"id":110,"title":"blog109","content":"this is blog content"},
    {"id":109,"title":"blog108","content":"this is blog content"}],
  "last":false,
  "totalPages":9,
  "totalElements":123,
  "size":15,
  "number":0,
  "first":true,
  "sort":[{
    "direction":"DESC",
    "property":"id",
    "ignoreCase":false,
    "nullHandling":"NATIVE",
    "ascending":false
  }],
  "numberOfElements":15
}

通过查询结果,我们可以知道:

  • 以id倒序排列的10条数据
  • 当前页不是最后一页,后面还有数据
  • 总共有9页
  • 每页大小为15
  • 当前页为第0页
  • 当前页是第一页
  • 当前页是以id倒序排列的
  • 当前页一共有15条数据

怎么样,信息是不是很丰富,代码是不是很简单,快点来尝试一下Jpa的分页查询吧。

之前我们学习了如何使用Jpa访问关系型数据库。比较完整Spring MVC和JPA教程请见Spring Data JPA实战入门Spring MVC实战入门

通过Jpa大大简化了我们对数据库的开发工作。但是,之前的例子中我们只提到了最简单的CRUD(增删改查)操作。实际上,Spring Data Jpa对于分页以及排序的查询也有着完美的支持,接下来,我们来学习如何通过Pageable来对数据库进行分页查询。

添加maven依赖

首先我们需要引入Jpa,数据库直接使用hsqldb内存数据库就可以了:

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.5.RELEASE</version>
    </parent>
    <groupId>tmy</groupId>
    <artifactId>demo.jpa.page</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>tmy-spring-jpa-page-demo</name>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</project>

继承PagingAndSortingRepository

Jpa的基本使用方法在如何使用Jpa访问关系型数据库已经介绍过,我们暂且跳过,这里我们直接来看接口BlogRepository的定义:

 

public interface BlogRepository extends PagingAndSortingRepository<Blog, Integer> {

    Page<Blog> findByDeletedFalse(Pageable pageable);

}

我们可以看到,BlogRepository定义了这样一个方法:Page<Blog> findByDeletedFalse(Pageable pageable);,我们主要关注它的参数以及返回值。

  • Pageable 是Spring Data库中定义的一个接口,该接口是所有分页相关信息的一个抽象,通过该接口,我们可以得到和分页相关所有信息(例如pageNumberpageSize等),这样,Jpa就能够通过pageable参数来得到一个带分页信息的Sql语句。
  • Page类也是Spring Data提供的一个接口,该接口表示一部分数据的集合以及其相关的下一部分数据、数据总数等相关信息,通过该接口,我们可以得到数据的总体信息(数据总数、总页数...)以及当前数据的信息(当前数据的集合、当前页数等)

Spring Data Jpa除了会通过命名规范帮助我们扩展Sql语句外,还会帮助我们处理类型为Pageable的参数,将pageable参数转换成为sql'语句中的条件,同时,还会帮助我们处理类型为Page的返回值,当发现返回值类型为Page,Spring Data Jpa将会把数据的整体信息、当前数据的信息,分页的信息都放入到返回值中。这样,我们就能够方便的进行个性化的分页查询。

Pageable只是一个抽象的接口,那么,家下来我们学习如何获得pageable对象。

通过参数生成Pageable对象

Pageable定义了很多方法,但其核心的信息只有两个:一是分页的信息(page、size),二是排序的信息。Spring Data Jpa提供了PageRequest的具体实现,Spring MVC提供了对Spring Data JPA非常好的支持,我们只提供分页以及排序信息即可:

 

@RequestMapping(value = "/params", method=RequestMethod.GET)
public Page<Blog> getEntryByParams(@RequestParam(value = "page", defaultValue = "0") Integer page,
        @RequestParam(value = "size", defaultValue = "15") Integer size) {
    Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = new PageRequest(page, size, sort);
    return blogRepository.findAll(pageable);
}

在这里,我们通过参数获得分页的信息,并通过Sort以及Direction告诉pageable需要通过id逆序排列。Spring MVC的介绍情移步这里:Spring MVC快速入门

这里可以看到,通过参数来得到一个pageable对象还是比较繁琐的,当查询的方法比较多的时候,会产生大量的重复代码。为了避免这种情况,Spring Data提供了直接生成pageable的方式。

直接获取Pageable对象

 

@RequestMapping(value = "", method=RequestMethod.GET)
public Page<Blog> getEntryByPageable(@PageableDefault(value = 15, sort = { "id" }, direction = Sort.Direction.DESC) 
    Pageable pageable) {
    return blogRepository.findAll(pageable);
}

我们可以看到,我们只需要在方法的参数中直接定义一个pageable类型的参数,当Spring发现这个参数时,Spring会自动的根据request的参数来组装该pageable对象,Spring支持的request参数如下:

  • page,第几页,从0开始,默认为第0页
  • size,每一页的大小,默认为20
  • sort,排序相关的信息,以property,property(,ASC|DESC)的方式组织,例如sort=firstname&sort=lastname,desc表示在按firstname正序排列基础上按lastname倒序排列

这样,我们就可以通过url的参数来进行多样化、个性化的查询,而不需要为每一种情况来写不同的方法了。

通过url来定制pageable很方便,但唯一的缺点是不太美观,因此我们需要为pageable设置一个默认配置,这样很多情况下我们都能够通过一个简洁的url来获取信息了。

Spring提供了@PageableDefault帮助我们个性化的设置pageable的默认配置。例如@PageableDefault(value = 15, sort = { "id" }, direction = Sort.Direction.DESC)表示默认情况下我们按照id倒序排列,每一页的大小为15。

返回结果

最后,让我们进入程序的根目录,运行命令mvn spring-boot:run将web应用启动起来,启动完成后,访问http://localhost:8080/页面,我们将看到如下结果:

 

{
  "content":[
    {"id":123,"title":"blog122","content":"this is blog content"},
    {"id":122,"title":"blog121","content":"this is blog content"},
    {"id":121,"title":"blog120","content":"this is blog content"},
    {"id":120,"title":"blog119","content":"this is blog content"},
    {"id":119,"title":"blog118","content":"this is blog content"},
    {"id":118,"title":"blog117","content":"this is blog content"},
    {"id":117,"title":"blog116","content":"this is blog content"},
    {"id":116,"title":"blog115","content":"this is blog content"},
    {"id":115,"title":"blog114","content":"this is blog content"},
    {"id":114,"title":"blog113","content":"this is blog content"},
    {"id":113,"title":"blog112","content":"this is blog content"},
    {"id":112,"title":"blog111","content":"this is blog content"},
    {"id":111,"title":"blog110","content":"this is blog content"},
    {"id":110,"title":"blog109","content":"this is blog content"},
    {"id":109,"title":"blog108","content":"this is blog content"}],
  "last":false,
  "totalPages":9,
  "totalElements":123,
  "size":15,
  "number":0,
  "first":true,
  "sort":[{
    "direction":"DESC",
    "property":"id",
    "ignoreCase":false,
    "nullHandling":"NATIVE",
    "ascending":false
  }],
  "numberOfElements":15
}

通过查询结果,我们可以知道:

  • 以id倒序排列的10条数据
  • 当前页不是最后一页,后面还有数据
  • 总共有9页
  • 每页大小为15
  • 当前页为第0页
  • 当前页是第一页
  • 当前页是以id倒序排列的
  • 当前页一共有15条数据

怎么样,信息是不是很丰富,代码是不是很简单,快点来尝试一下Jpa的分页查询吧。

转载于:https://www.cnblogs.com/Andrew520/p/9413160.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值