在本系统中,学生的学号除了不能为null以外,其必然也是唯一的。在spring data jpa中如下表示: entity/Student.java ``` @Column(nullable = false, unique = true➊) private String sno; ``` * ➊ 该属性的默认值为false,设置为true时表示该字段的值具有唯一性 ## 测试 entity/StudentTest.java ``` @Test public void snoUniqueTest() { this.studentRepository.save(this.student); ① this.before(); ② this.studentRepository.save(this.student); ③ } ``` * ① 正常的保存一个学生 * ② 调用this.before,重新生成一个学号相同的新学生 * ③ 保存这个新学生,由于这个新学生与第一次保存的学生学号相同,那么我们预期会发生一个异常 启动测试后我们将得到如下异常: ``` org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_cxffpo742xolsmubc0erwwf9m]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement ...此处省略多行冗余信息 Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '032282' for key 'UK_cxffpo742xolsmubc0erwwf9m' ``` 同null错误一样,unique唯一性校验产生了DataIntegrityViolationException,在报错的详细信息中显示:在关键字'UK_cxffpo742xolsmubc0erwwf9m'上发现了重复条目032282(我们测试学生的学号)。这个关键字 `UK_cxffpo742xolsmubc0erwwf9m`是spring为我们自动生成的,我们可以启动后台应用: ![](https://img.kancloud.cn/b3/d3/b3d3d3904bb9225bbd56c87e989fd71c_705x72.png) 然后使用navicat来查看生成的student表: ![](https://img.kancloud.cn/ca/a7/caa71ce55ebe6928a02dee20c36b8c1b_802x224.png) 点击`索引`选项卡: ![](https://img.kancloud.cn/31/ba/31baf9653f4a9a83c16193536c604e71_1508x218.png) 发现该字符串正是spring为sno字段生成的索引名,同时我们还观察到spring自动将其索引类型设置为UNIQUE,而此时如果新增的sno与历史数据重复的话,便会发生数据校验错误。 ### 完成测试 确认了异常的类型后,我们使用try catch的方式获取该异常,并断言发生了异常。 ``` @Test public void snoUniqueTest() { this.studentRepository.save(this.student); this.before(); boolean called = false; try { this.studentRepository.save(this.student); } catch (DataIntegrityViolationException e) { called = true; } Assertions.assertThat(called).isTrue(); } ``` 我们在此方法中先后调用了两次`this.studentRepository.save`,如果使用`@Test(expected = DataIntegrityViolationException.class)`来处理此测试,那么即使测试通过,我们是无法确认该异常是第一次调用引发的还是第二次调用引发的(特别当其它的成员修正我们的代码或是一个月以后的自己修正自己代码的时候),所以在此我们使用`try catch`的方法来断言异常。 # 参考文档 | 名称 | 链接 | 预计学习时长(分) | | --- | --- | --- | | 源码地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step4.5.7](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step4.5.7) | - | | @Column | [https://docs.oracle.com/javaee/7/api/javax/persistence/Column.html](https://docs.oracle.com/javaee/7/api/javax/persistence/Column.html) | 5 |