关于我的方法 accountRepo.deleteAll()
返回错误。
2020-06-04 15:37:05.069 ERROR 78168 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ОШИБКА: UPDATE or DELETE in table "account" violates foreign key constraint "fk8k31xl4ld2m810mxfkqp2xg8g" from table "tokens"
Details: on a key (account_id)=(2) there are still links in the table "tokens".
2020-06-04 15:37:05.071 INFO 78168 --- [ main] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
可能是什么问题?这种情况发生在创建一个注册用户的后请求时,该用户将属于 accountRepo
我的测试和后请求。
@Test
@Throws(Exception::class)
fun shouldRegistrationExpected201() {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
val request = HttpEntity<String>("{\"username\": \"holker228\", \"password\": \"123456QQwerty&&\",\"email\":\"[email protected]\",\"is_collective\": \"false\" }", headers)
val responseEntity = restTemplate.postForEntity("http://localhost:$port/api/user/registration", request, String::class.java)
assertEquals(responseEntity.statusCode, HttpStatus.CREATED)
}
这个问题似乎是在你的数据库中配置的约束。另外,你用的是哪一个?在你的特殊情况下,约束条件不允许使用 DELETE
(UPDATE
?)操作,因为你要删除的行似乎在另一个表中有依赖行。
例如,想象你有一个表 "用户 "和 "评论"。
users:
-------------
| ID | Name |
-------------
| 1 | Max |
-------------
| 2 | Vova |
-------------
| 3 | Vlad |
-------------
comments:
---------------------------------
| ID | User ID | Text |
---------------------------------
| 1 | 1 | Max was here! |
---------------------------------
| 2 | 1 | Vova + Vlad = ❤️ |
---------------------------------
| 3 | 2 | Don't listen to Max! |
---------------------------------
这里,如果配置了约束,你就不能从 "用户 "中删除Max(1)或Vova(2),因为它们有注释。想象一下,你正在渲染一个HTML页面,你需要渲染一个评论的作者名?如果作者被删除,你会怎么做?(好吧,你可以使用 "匿名",但我们不要去想它)。你既不能改Max的ID,也不能改Vova的ID,原因同上。所以这就是约束的作用:它们可以防止这种不一致的情况发生。
处理这种情况的方法。
CASCADE
对于 DELETE
s. 看一看 本回答例如