"Failed to execute DbAction.DeleteRoot" 和 JDBC?

"Failed to execute DbAction.DeleteRoot" with JDBC?

我有一个带有 "deleteItem" 方法的 JDBC 存储库,但是当我通过 Postman 触发该方法时,我收到一个奇怪的错误:"Failed to execute DbAction.DeleteRoot"

一些项目删除没有问题,只有一部分数据触发了这个错误。

这是我的@Repository 代码的范围:

@Repository
interface ItemRepository: CrudRepository<Item, UUID>
{
    @Query( "select * from item_data where scopes @> :scopes")
    fun findItemsByScope(@Param("scopes") scope: String): List<Item>
}

这是实现它的 @Component(由我的 API 调用)

@Component
class RepositoryItemPersistenceAdapter(
        private val repository: ItemRepository
){

    fun getItemsByScope(scope: String) : List<Item> =
       repository.findItemsByScope(scope)

    fun deleteItem(id: UUID) = repository.deleteById(id)

    fun getAllItems(): List<Item> = repository.findAll()

}

这个问题最终证明不是基于代码的,而是基于模式的!

项目数据库 ID 在另外两个数据库中用作外键。尝试按 ID 删除项目会引发错误,因为当外键停止引用任何内容时,它会孤立其他 table 中的行。

异常详细信息(不作为 500 的一部分返回)如下:

org.postgresql.util.PSQLException: ERROR: update or delete on table "item_data" violates foreign key constraint "identity_mapping_id_fkey" on table "identity_mapping" Detail: Key (id)=(99304a5d-5bcc-4f31-a192-625ed8c9059b) is still referenced from table "identity_mapping".

这也是为什么有些数据删除得很好的原因 -- 它在映射中没有对应的条目 table,因此在删除过程中没有触发此错误。

最终的解决方案是在删除之前检查外键,在删除之前删除或更新相应的行。