Spring Boot 2.x 小新功能 – Spring Data Web configuration
Spring Boot 2.x 小新功能 – Spring Data Web configuration
摘要: 原創出處 www.bysocket.com 「泥瓦匠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 中自定義分頁和排序相關的預設值和引數名。
具體見地址: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 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)。
最重要的是,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
歡迎掃一掃我的公眾號關注 — 及時得到部落格訂閱哦!
— http://www.bysocket.com/ —
— https://github.com/JeffLi1993 —