如果实体不存在,如何告诉 Springdata-repository 的 delete 方法不抛出异常? [英] How to I tell a Springdata-repository's delete method to not throw an exception if an entity does not exists?

查看:20
本文介绍了如果实体不存在,如何告诉 Springdata-repository 的 delete 方法不抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SpringData 的存储库.如果我尝试通过不存在或从未存在的 ID 删除实体,则会引发异常.由于我不想在删除实体之前检查它是否存在,因此它会静默失败会很好.这会更容易,因为可观察的行为是相同的 - 在调用之后实体不再存在.是被删除了还是从未存在过,我不在乎.

I am using SpringData's repository. If I try to delete an entity via an ID which does not exist or never existed it throws an exception. Since I do not want to check whether the entity exists before I delete it, it would be nice that it would fail silently. It would make it easier because the observable behavior is the same - after the call the entity does not exists anymore. Whether it has been deleted or never existed, I do not care.

有没有办法修改 delete(EntityId) 的默认行为,使其在实体不存在的情况下不会抛出异常?

Is there a way to modify default behavior of delete(EntityId) so it won't throw an exception, if entity does not exsist?

SpringData 的删除文档 说如果实体不存在它会抛出异常.

Documentation of SpringData's delete says that it will throw an exception if an entity does not exist.

推荐答案

更新答案(否决后)

我的原始答案(如下)实际上是错误的:我对这个问题的理解也受到官方 JavaDoc 中对 EmptyResultDataAccessException 的缺失引用的影响(如 Adrian Baker 在他的评论中所报告的).

My original answer (below) is actually wrong: my understanding of the question was influenced also by the missing reference to the EmptyResultDataAccessException in the official JavaDoc (as reported by Adrian Baker in his comment).

所以这个问题的更好解决方案可能是 Yamashiro Rion 建议的方案

So a better solution to this issue could be the one suggested by Yamashiro Rion

if (repository.existsById(entityId)) {
    repository.deleteById(entityId);
}

或者这个(没有if,但可能表现更差):

or this one (without the if, but probably worse performing):

repository.findById(entityId)
    .map(repository::delete)

<小时>

原始(错误)答案

JavaDocs 表示,如果提供的参数(id、实体、Iterable)为 null 而不是 如果实体不是,则将抛出 IllegalArgumentException存在.

JavaDocs says that an IllegalArgumentException will be thrown if the provided argument (id, entity, Iterable<T>) is null and not if entity does not exsits.

如果您需要避免 IllegalArgumentException,您可以实现一个自定义删除方法来检查 id != null:

If you need to avoid the IllegalArgumentException you could implement a custom delete method that checks id != null:

public void customDelete(ID id) {
    if(id != null){
        this.delete(id);
    }
}

看看这个文档部分如果您不知道如何添加Spring Data 存储库的自定义实现"

Take a look to this docs section if you don't know how to add "Custom implementations for Spring Data repositories"

这篇关于如果实体不存在,如何告诉 Springdata-repository 的 delete 方法不抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆