春季jparepository仅在存在ID时才执行删除并避免种族条件

发布于 2025-02-08 08:44:21 字数 580 浏览 2 评论 0原文

我的位置如下:

我在春季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 Id
public 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我太投入 2025-02-15 08:44:21

如果您使用的是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 the EntityManager, consider using delete (which will just return with no exception being thrown in case the ID is unknown).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文