啟動數據庫、后臺、前后并準備一些基礎的測試數據后,來查看一個前面單元測試中遺漏的BUG。

在編輯學生的過程時,可以任意的變更學位的位數,任意的修改學生的姓名。而完全忽略掉了本章第五節新增學生時對學號、姓名的長度做的校驗。相信任何程序員都接受不了當前的現實。
只所以會這樣還要看看歷史上對學號、姓名進行校驗的代碼:
entity/Student.java
```java
/**
* 在實體保存到數據庫以前,執行1次
* 1. 校驗name 字段長度為2-20
* 2. 校驗sno 字段長為為6
*/
@PrePersist // ★
public void perPersis() {
if (this.name != null ) {
if (this.name.length() < 2) {
throw new DataIntegrityViolationException("name length less than 2");
}
if (this.name.length() > 20) {
throw new DataIntegrityViolationException("name length more than 20");
}
}
if (this.sno != null) {
if (this.sno.length() != 6) {
throw new DataIntegrityViolationException("sno length must be 6");
}
}
}
```
* ★ 重點在這。 @PrePersist注解的作用時,在持久化(保存)之前。而非在更新之前。
雖然在代碼層面,保存與更新都是調用了`save`方法。但hibernate還是能自動的區分出當前執行的是保存操作還是更新操作的。
# @PreUpdate
`@PrePersist`中`@`代表注解,`Pre`意為在什么之前,`Persist`譯為持久化也就是保存。起到的作用是:在數據保存之前執行此注解下的內容。Hibernate同時還提供了另一個用于更新之前執行某個方法的注解:`@PreUpdate`。測試如下:
entity/Student.java
```java
@PreUpdate
public void perUpdate() {
System.out.println("正在執行更新操作: " + this.id.toString());
}
```
然后臨時將`src/main/resources/application.propertions`中的`spring.jpa.hibernate.ddl-auto=create-drop`改為`spring.jpa.hibernate.ddl-auto=update`。然后重新啟動后臺應用并于前面重新進行測試數據的初始化工作。
> [info] create-drop:啟動應用時創建數據表,停止應用時刪除數據表。update:啟動應用時更新數據表(如有更新內容),停止應用時什么也不做。
測試如下:

接下來,可以將prePersist()方法中的代碼復制到 preUpdate()方法中來達到與新增學生相同的校驗效果。也可以這樣:
entity/Student.java
```java
@PreUpdate
public void perUpdate() {
this.perPersis();
}
```
也可以達到相同的驗證效果。

# 單元測試
雖然前臺后依賴式開發(前臺的開發依賴于后臺,后臺的開發也依賴于前臺)貌似很簡單,但每次修改完代碼都要用鼠標鍵盤執行相同的操作,這對做為不甘寂寞的程序員而言卻顯得難以接受。相較于這種依賴式的,每次變更代碼后都要復要的操作鼠標鍵盤式的測試,筆者更愿意選擇用代碼來測試代碼的方式。
有了新增學生的測試經驗,編輯的學生的測試也就不難了。測試的思想為:先新增一個學生,然后分別使用不符合要求的姓名、學號來更新此學生,斷言在更新過程中發生異常。最后再用符合要求的姓名、學號來更新此學生,斷言更新成功。
請按上述思路參考新增學生的校驗嘗試自行完成單元測試。**提示:**更新操作校驗失敗時將發生`TransactionSystemException`異常。
<hr>
參考代碼如下:
entity/StudentTest.java
```java
@Test(expected = TransactionSystemException.class)
public void updateNameLengthToLongTest() {
// 第一次調用save執行保存操作
this.studentRepository.save(student);
this.student.setName("123456789012345678901");
// 第二次調用save執行更新操作
this.studentRepository.save(student);
}
@Test(expected = TransactionSystemException.class)
public void updateNameLengthToShortTest() {
this.studentRepository.save(student);
this.student.setName("1");
this.studentRepository.save(student);
}
/**
* 先后執行100次隨機學號
* 當學號為6位時,更新成功
* 當學號不是6位時,更新時發生異常
*/
@Test
public void updateSnoLengthTest() {
this.studentRepository.save(student);
for (int i = 1; i <= 100; i++) {
this.student.setSno(RandomString.make(i));
boolean called = false;
try {
this.studentRepository.save(student);
} catch (TransactionSystemException e) {
called = true;
}
if (i != 6) {
Assertions.assertThat(called).isTrue();
} else {
Assertions.assertThat(called).isFalse();
}
}
}
```
除此以外Spring還提供了功能相似的 `PostLoad`、`PostPersist`、`PostRemove`、`PreRemove`注解,官方文檔說明如下:
| Type | Description |
| --- | --- |
| @PrePersist | Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation. |
| @PreRemove | Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation. |
| @PostPersist | Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed. |
| @PostRemove | Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation. |
| @PreUpdate | Executed before the database UPDATE operation. |
| @PostUpdate | Executed after the database UPDATE operation. |
| @PostLoad | Executed after an entity has been loaded into the current persistence context or an entity has been refreshed. |
請自行翻譯嘗試。
# 參考文檔
| 名稱 | 鏈接 | 預計學習時長(分) |
| --- | --- | --- |
| 源碼地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step4.7.9](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step4.7.9) | - |
| Hibernate: Entity listeners and Callback methods | [https://docs.jboss.org/hibernate/core/4.0/hem/en-US/html/listeners.html#d0e2985](https://docs.jboss.org/hibernate/core/4.0/hem/en-US/html/listeners.html#d0e2985) | 10 |
- 序言
- 第一章:Hello World
- 第一節:Angular準備工作
- 1 Node.js
- 2 npm
- 3 WebStorm
- 第二節:Hello Angular
- 第三節:Spring Boot準備工作
- 1 JDK
- 2 MAVEN
- 3 IDEA
- 第四節:Hello Spring Boot
- 1 Spring Initializr
- 2 Hello Spring Boot!
- 3 maven國內源配置
- 4 package與import
- 第五節:Hello Spring Boot + Angular
- 1 依賴注入【前】
- 2 HttpClient獲取數據【前】
- 3 數據綁定【前】
- 4 回調函數【選學】
- 第二章 教師管理
- 第一節 數據庫初始化
- 第二節 CRUD之R查數據
- 1 原型初始化【前】
- 2 連接數據庫【后】
- 3 使用JDBC讀取數據【后】
- 4 前后臺對接
- 5 ng-if【前】
- 6 日期管道【前】
- 第三節 CRUD之C增數據
- 1 新建組件并映射路由【前】
- 2 模板驅動表單【前】
- 3 httpClient post請求【前】
- 4 保存數據【后】
- 5 組件間調用【前】
- 第四節 CRUD之U改數據
- 1 路由參數【前】
- 2 請求映射【后】
- 3 前后臺對接【前】
- 4 更新數據【前】
- 5 更新某個教師【后】
- 6 路由器鏈接【前】
- 7 觀察者模式【前】
- 第五節 CRUD之D刪數據
- 1 綁定到用戶輸入事件【前】
- 2 刪除某個教師【后】
- 第六節 代碼重構
- 1 文件夾化【前】
- 2 優化交互體驗【前】
- 3 相對與絕對地址【前】
- 第三章 班級管理
- 第一節 JPA初始化數據表
- 第二節 班級列表
- 1 新建模塊【前】
- 2 初識單元測試【前】
- 3 初始化原型【前】
- 4 面向對象【前】
- 5 測試HTTP請求【前】
- 6 測試INPUT【前】
- 7 測試BUTTON【前】
- 8 @RequestParam【后】
- 9 Repository【后】
- 10 前后臺對接【前】
- 第三節 新增班級
- 1 初始化【前】
- 2 響應式表單【前】
- 3 測試POST請求【前】
- 4 JPA插入數據【后】
- 5 單元測試【后】
- 6 惰性加載【前】
- 7 對接【前】
- 第四節 編輯班級
- 1 FormGroup【前】
- 2 x、[x]、{{x}}與(x)【前】
- 3 模擬路由服務【前】
- 4 測試間諜spy【前】
- 5 使用JPA更新數據【后】
- 6 分層開發【后】
- 7 前后臺對接
- 8 深入imports【前】
- 9 深入exports【前】
- 第五節 選擇教師組件
- 1 初始化【前】
- 2 動態數據綁定【前】
- 3 初識泛型
- 4 @Output()【前】
- 5 @Input()【前】
- 6 再識單元測試【前】
- 7 其它問題
- 第六節 刪除班級
- 1 TDD【前】
- 2 TDD【后】
- 3 前后臺對接
- 第四章 學生管理
- 第一節 引入Bootstrap【前】
- 第二節 NAV導航組件【前】
- 1 初始化
- 2 Bootstrap格式化
- 3 RouterLinkActive
- 第三節 footer組件【前】
- 第四節 歡迎界面【前】
- 第五節 新增學生
- 1 初始化【前】
- 2 選擇班級組件【前】
- 3 復用選擇組件【前】
- 4 完善功能【前】
- 5 MVC【前】
- 6 非NULL校驗【后】
- 7 唯一性校驗【后】
- 8 @PrePersist【后】
- 9 CM層開發【后】
- 10 集成測試
- 第六節 學生列表
- 1 分頁【后】
- 2 HashMap與LinkedHashMap
- 3 初識綜合查詢【后】
- 4 綜合查詢進階【后】
- 5 小試綜合查詢【后】
- 6 初始化【前】
- 7 M層【前】
- 8 單元測試與分頁【前】
- 9 單選與多選【前】
- 10 集成測試
- 第七節 編輯學生
- 1 初始化【前】
- 2 嵌套組件測試【前】
- 3 功能開發【前】
- 4 JsonPath【后】
- 5 spyOn【后】
- 6 集成測試
- 7 @Input 異步傳值【前】
- 8 值傳遞與引入傳遞
- 9 @PreUpdate【后】
- 10 表單驗證【前】
- 第八節 刪除學生
- 1 CSS選擇器【前】
- 2 confirm【前】
- 3 功能開發與測試【后】
- 4 集成測試
- 5 定制提示框【前】
- 6 引入圖標庫【前】
- 第九節 集成測試
- 第五章 登錄與注銷
- 第一節:普通登錄
- 1 原型【前】
- 2 功能設計【前】
- 3 功能設計【后】
- 4 應用登錄組件【前】
- 5 注銷【前】
- 6 保留登錄狀態【前】
- 第二節:你是誰
- 1 過濾器【后】
- 2 令牌機制【后】
- 3 裝飾器模式【后】
- 4 攔截器【前】
- 5 RxJS操作符【前】
- 6 用戶登錄與注銷【后】
- 7 個人中心【前】
- 8 攔截器【后】
- 9 集成測試
- 10 單例模式
- 第六章 課程管理
- 第一節 新增課程
- 1 初始化【前】
- 2 嵌套組件測試【前】
- 3 async管道【前】
- 4 優雅的測試【前】
- 5 功能開發【前】
- 6 實體監聽器【后】
- 7 @ManyToMany【后】
- 8 集成測試【前】
- 9 異步驗證器【前】
- 10 詳解CORS【前】
- 第二節 課程列表
- 第三節 果斷
- 1 初始化【前】
- 2 分頁組件【前】
- 2 分頁組件【前】
- 3 綜合查詢【前】
- 4 綜合查詢【后】
- 4 綜合查詢【后】
- 第節 班級列表
- 第節 教師列表
- 第節 編輯課程
- TODO返回機制【前】
- 4 彈出框組件【前】
- 5 多路由出口【前】
- 第節 刪除課程
- 第七章 權限管理
- 第一節 AOP
- 總結
- 開發規范
- 備用