Spring Boot 2.x 小新功能 – Spring Data Web configuration
本文提綱
一、前言
二、運行 chapter-5-spring-boot-paging-sorting 工程
三、chapter-5-spring-boot-paging-sorting 工程配置詳解
四、小結
運行環境:
Mac OS 10.12.x
JDK 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 中自定義分頁和排序相關的默認值和參數名。
具體見地址:https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M2-Release-Notes
二、運行工程
git clone 下載工程 spring-boot-core-book-demo ,項目地址見 GitHub -
https://github.com/JeffLi1993/spring-boot-core-book-demo。
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 https://localhost:8080/users/create
Content-Type: application/json
{
"name":"javaer",
"age":22,
"birthday":"2019-09-19"
}
如圖:
重複上麵步驟,新增用戶 13 個。
然後,調用分頁查詢用戶列表接口:
GET https://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="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://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 https://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 -
https://github.com/JeffLi1993/spring-boot-core-book-demo。
四、小結
還是溫故知新,加上一些 Spring 2.x 小新功能 - Spring Data Web configuration
上一篇:《「北京站」ArchData 技術峰會-文末社區送福利》
最好的讚賞
就是你的關注
最後更新:2017-09-21 13:02:52