Spring Boot 2.x 小新功能 – Spring Data Web configuration

1,426 阅读6分钟
原文链接: zhuanlan.zhihu.com
摘要: 原创出处 Spring Boot 2.x 小新功能 - Spring Data Web configuration 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!

不赚钱,是一个创业者的最大耻辱。
先赚钱,活得好,再谈发展,这才是最重要的

本文提纲

一、前言

二、运行 chapter-5-spring-boot-paging-sorting 工程

三、chapter-5-spring-boot-paging-sorting 工程配置详解

四、小结

运行环境

Mac OS 10.12.xJDK 8 +Spring Boot 2.0.0.M4

一、前言

Spring 2.x 更新了一个小小的功能即:

Spring Data Web configuration
Spring Boot exposes a new spring.data.web configuration namespace that allows to easily configure paging and sorting.

就是说,可以在 application.properties 中自定义分页和排序相关的默认值和参数名。

具体见地址:github.com/spring-proje

二、运行工程

git clone 下载工程 spring-boot-core-book-demo ,项目地址见 GitHub github.com/JeffLi1993/…

1. 工程结构

项目结构如下图所示:

org.spring.springboot.controller - Controller 层
org.spring.springboot.domain - 实体类及数据操作层 DAO
org.spring.springboot.service - 业务逻辑层
PagingSortingApplication - 应用启动类
application.properties - 应用配置文件,应用启动会自动读取配置

具体详细结构如下:

├── pom.xml
└── src
    ├── main
       ├── java
          └── spring
              └── boot
                  └── core
                      ├── PagingSortingApplication.java
                      ├── domain
                         ├── User.java
                         └── UserRepository.java
                      ├── service
                         ├── UserService.java
                         └── impl
                             └── UserServiceImpl.java
                      └── web
                          └── UserController.java
       └── resources
           ├── application.properties
           └── static
    └── test

2.编译工程

在项目根目录 spring-boot-core-book-demo,运行 maven 指令去编译工程:

mvn clean install

3.运行工程

在 chapter-5-spring-boot-paging-sorting 工程中,右键运行 PagingSortingApplication 应用启动类的 main 函数。待控制台日志中看到启动成功后。

在 PostMan 工具中,新增用户几个:

POST http://localhost:8080/users/create
Content-Type: application/json
{
    "name":"javaer",
    "age":22,
    "birthday":"2019-09-19"
}

如图:

重复上面步骤,新增用户 13 个。

然后,调用分页查询用户列表接口:

GET http://localhost:8080/users?pageNumber=1&pageSize=3&orderBy=id,desc

如图:

可见,查询出第 2 页的用户数据,并且按 id 倒序。还有可见,返回了分页相关的数据:每页大小(这里是 3 个)、排序、总个数和总页数等。

从应用日志中也可以看出对应的 HQL :

2017-09-20 14:46:16.630  INFO 14593 --- [nio-8080-exec-4] s.b.core.service.impl.UserServiceImpl    :  
 分页查询用户 PageNumber = 1 PageSize = 3
2017-09-20 14:46:16.703  INFO 14593 --- [nio-8080-exec-4] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.birthday as birthday3_0_, user0_.name as name4_0_ from user user0_ order by user0_.id desc limit ? offset ?
Hibernate: select count(user0_.id) as col_0_0_ from user user0_

三、工程配置详解

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <groupId>spring.boot.core</groupId>
    <artifactId>chapter-5-spring-boot-paging-sorting</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>chapter-5-spring-boot-paging-sorting</name>
    <description>第五章数据分页排序案例</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!-- Web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 单元测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Spring Data JPA 依赖 :: 数据持久层框架 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- h2 数据源连接驱动 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!-- Spring Boot Maven 插件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.5.1.RELEASE</version>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

简单依赖了 Web 依赖、Spring Data JPA 依赖 :: 数据持久层框架,并且使用 h2 内存式数据源。

2.在 application.properties 应用配置文件,增加相关分页排序参数

## 是否显示 SQL 语句
spring.jpa.show-sql=true

## DATA WEB 相关配置 {@link SpringDataWebProperties}
## 分页大小 默认为 20
spring.data.web.pageable.default-page-size=3
## 当前页参数名 默认为 page
spring.data.web.pageable.page-parameter=pageNumber
## 当前页参数名 默认为 size
spring.data.web.pageable.size-parameter=pageSize
## 字段排序参数名 默认为 sort
spring.data.web.sort.sort-parameter=orderBy

关于 Data Web 分页和排序相关的配置:

设置 spring.data.web.pageable.default-page-size 可修改分页大小,默认分页大小为 20
设置 spring.data.web.pageable.page-parameter 可修改当前页参数名,默认参数名为 page
设置 pring.data.web.pageable.size-parameter 可修改当前页参数名,默认参数名为 size
设置 spring.data.web.sort.sort-parameter 可修改字段排序参数名,默认参数名为 sort

这里我们修改了各个参数名。如果什么都不设置的话,分页排序查询接口地址如下:

GET http://localhost:8080/users?page=1&size=3&sort=id,desc

这里就是,Spring 2.x 更新了一个小小的功能即:

就是说,可以在 application.properties 中自定义分页和排序相关的默认值和参数名。

3.用户持久层操作接口 UserRepository

/**
 * 用户持久层操作接口
 *
 * Created by bysocket on 18/09/2017.
 */
public interface UserRepository extends PagingAndSortingRepository<User, Long> {

}

接口只要继承 PagingAndSortingRepository 类即可。默认会提供很多实现,比如 CRUD 相关的实现。支持的默认方法有: count(), findAll(), findOne(ID), delete(ID), deleteAll(), exists(ID), save(DomainObject), save(Iterable<DomainObject>)。

最重要的是,

PagingAndSortingRepository 提供了两个接口

   Iterable<T> findAll(Sort sort);
   Page<T> findAll(Pageable pageable);

用来支持 分页 和 排序 的获取数据接口。

4.用户业务层实现类 UserServiceImpl

/**
 * User 业务层实现
 *
 * Created by bysocket on 18/09/2017.
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserRepository userRepository;

    @Override
    public Page<User> findByPage(Pageable pageable) {
        LOGGER.info(" \n 分页查询用户:"
                + " PageNumber = " + pageable.getPageNumber()
                + " PageSize = " + pageable.getPageSize());
        return userRepository.findAll(pageable);
    }

    @Override
    public User insertByUser(User user) {
        LOGGER.info("新增用户:" + user.toString());
        return userRepository.save(user);
    }
}

这边没有具体的业务操作,就打印了对应业务层分页相关的参数。

5.用户控制层 UserController

/**
 * 用户控制层
 *
 * Created by bysocket on 18/09/2017.
 */
@RestController
@RequestMapping(value = "/users")     // 通过这里配置使下面的映射都在 /users
public class UserController {

    @Autowired
    UserService userService;          // 用户服务层

    /**
     *  获取用户分页列表
     *    处理 "/users" 的 GET 请求,用来获取用户分页列表
     *    通过 @RequestParam 传递参数,进一步实现条件查询或者分页查询
     *
     *    Pageable 支持的分页参数如下
     *    page - 当前页 从 0 开始
     *    size - 每页大小 默认值在 application.properties 配置
     */
    @RequestMapping(method = RequestMethod.GET)
    public Page<User> getUserPage(Pageable pageable) {
        return userService.findByPage(pageable);
    }

    /**
     *  创建用户
     *    处理 "/users" 的 POST 请求,用来获取用户列表
     *    通过 @RequestBody 绑定实体类参数
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public User postUser(@RequestBody User user) {
        return userService.insertByUser(user);
    }

}

这里实现了两个 HTTP 服务接口。这次主要在实现 getUserPage 方法,利用分页参数来进行。

page - 当前页 从 0 开始

size - 每页大小 默认值在 application.properties 配置

其他不明白的,可以git clone 下载工程 spring-boot-core-book-demo,工程代码注解很详细,项目地址见 GitHub -

github.com/JeffLi1993/s

四、小结

还是温故知新,加上一些 Spring 2.x 小新功能 – Spring Data Web configuration