How to catch OptimisticLockException in JPA

本小妞迷上赌 提交于 2019-12-11 02:07:41

问题


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";
            }

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?


回答1:


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.

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



来源:https://stackoverflow.com/questions/17203452/how-to-catch-optimisticlockexception-in-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!