如何在JPA中捕获OptimisticLockException [英] How to catch OptimisticLockException in JPA

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

问题描述

我在这里读到了一些关于在无状态会话bean中使用的 OptimisticLockException 和JPA的问题。

I've read out a couple of questions here regarding the OptimisticLockException with JPA, used in an stateless session bean. It is thrown, but not where I expect it obviously.

这里是我期望得到异常的代码:

Here is the code where I expect to get the exception:

            try
            {
                productFacade.edit(product);
            }
            catch(Exception {
                return "lock";
            }


b $ b

productFacade 是使用NetBeans生成的,它是一个具有本地接口的EJB,它实现了一个 AbstractFacade 被调用,我应该在哪里处理异常?

The productFacade is generated with NetBeans and it is an EJB with a local interface, an it implements an AbstractFacade abstract class. As far as I read, this has something to do with transactions in JPA. Because the exception is thrown after the method this code snippet is in is left, not after edit() is called. Where should I than handle the exception?

此外,我需要事务机制以后,因为我需要更新我发现了一些代码示例,但是这让我想知道我应该如何使用事务?

Also, I will be needing the transaction mechanism for later, because I will need to update multiple products (or none if some is locked). I've found some code examples, but this leaves me wondering how should I work with transactions?

推荐答案

在事务提交之前不会抛出锁定错误,因此您需要在SessionBean之外处理它或使用容器管理的事务。

The lock error will not be thrown until the transaction commits. So you would need to handle it outside of your SessionBean or use a container managed transaction.

或者,你可以调用你的JPA EntityManager上的flush(),然后会抛出错误。

Or, you could just call flush() on your JPA EntityManager, then the error will be thrown.

这篇关于如何在JPA中捕获OptimisticLockException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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