JPA:处理OptimisticLockException的模式 [英] JPA: pattern for handling OptimisticLockException

查看:1445
本文介绍了JPA:处理OptimisticLockException的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在(REST)Web服务中处理OLE的正确模式是什么?这是我现在正在做的,例如

what is the correct pattern for handling OLE in a (REST) web service? this is what i'm doing now, for example,

protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ...
    ...
    ...

    try {
        try {
            em.getTransaction().begin();
            // ... remove the entity
            em.getTransaction().commit();
        } catch (RollbackException e) {
            if (e.getCause() instanceof OptimisticLockException) {
                try {
                    CLog.e("optimistic lock exception, waiting to retry ...");
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
                doDelete(request, response);
                return;
            }
        }

        // ... write response

    } catch (NoResultException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return;
    } finally {
        em.close();
    }
}

无论何时你在代码中看到一个睡眠,好的机会是不正确的。有没有更好的办法来处理这个?

anytime you see a sleep in the code, there's a good chance it's incorrect. is there a better way to handle this?

另一种方法是立即将故障发送回客户端,但我不想让他们担心。正确的事情似乎是做任何需要,使请求在服务器上成功,即使它需要一段时间。

another approach would be to immediately send the failure back to the client, but i'd rather not have them worry about it. the correct thing seems to do whatever is required to make the request succeed on the server, even if it takes a while.

感谢。

推荐答案

如果您遇到乐观锁定例外,则意味着某些其他事务对您尝试更新/删除的实体有已提交更改。由于其他事务已提交,立即重试可能有很好的成功机会。

If you get an optimistic locking exception, it means that some other transaction has committed changes to entities you were trying to update/delete. Since the other transaction has committed, retrying immediately might have a good chance to succeed.

我也会使方法在N次尝试后失败,而不是等待StackOverflowException发生。

I would also make the method fail after N attempts, rather than waiting for a StackOverflowException to happen.

这篇关于JPA:处理OptimisticLockException的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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