春季jparepository仅在存在ID时才执行删除并避免种族条件
我的位置如下:
我在春季JPA项目中有@entity类成分。 我想通过记录ID实现在DB记录上执行删除操作的方法 public boolean deleteingredient(字符串ID)
,如果可能的话,请避免处理不存在的ID的异常。
不幸的是,在删除记录之前,我可以在此领域找到的唯一建议是基于ID查询的事实
ingredientRepository.findById(id).ifPresent(x -> ingredientRepository.deleteById(id));
,或者
if(ingredientRepository.existsById(id)){
ingredientRepository.deleteById(id);
}
我认为很容易竞争条件(其他线程可能会在此询问存在后删除记录。 最好的方法真的只是将其包裹在trycatch块中并处理eyaterResultDataAccessexception
在不存在给定ID的情况下记录下来吗?
my situtation is as follows:
I have @Entity class Ingredient in my Spring JPA Project.
I would like to implement a method performing delete operation on DB record by record Idpublic boolean deleteIngredient(String id)
and if possible avoid handling exceptions for non-existent Ids.
Unfortunately the only recommendations I can find in this area are based on the fact of querying by Id before deleting record e.g.
ingredientRepository.findById(id).ifPresent(x -> ingredientRepository.deleteById(id));
or
if(ingredientRepository.existsById(id)){
ingredientRepository.deleteById(id);
}
which I believe are prone to race conditions (other thread may delete record after this one queries for existence.
Is the best approach really just wrapping it in a try-catch block and handling EmptyResultDataAccessException
in case record with given Id does not exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用的是JPA,则需要在持久性上下文中标记删除实体(例如,数据库中不在数据库中)。请记住,JPA存储库遵循ORM范式,并且没有直接在记录上行动。
任何种族条件都将在持久性上下文级别上处理。
如果您使用
@transactional
,那么您将是安全的。Also if you don't want the explicit error thrown by
If you are using JPA, you need the entity to be marked for deletion in the persistence context (e.g. not in the Database). Keep in mind JPA Repository follows the ORM paradigm and is not acting on the record directly.
Any race conditions will be handled on the persistence context level.
If you use
@Transactional
and you will be safe.Also if you don't want the explicit error thrown by
deleteById
, when the ID is not known to theEntityManager
, consider usingdelete
(which will just return with no exception being thrown in case the ID is unknown).