【问题标题】:Exception not cuaght with Entity ManagerEntitymanager 未捕获异常
【发布时间】:2014-04-10 09:28:29
【问题描述】:

我的 EJB 中有一个实体管理器

@PersistenceContext(unitName = "cnsbEntities")
private EntityManager em;

我填充了一个对象,然后将它提交到我的数据库中,但如果我有一个异常,对于重复的 ID,我无法捕获它,我不知道为什么。

    try{
      em.merge(boelLog);
    } catch (Exception e){
        System.out.println("Generic Exception");
    }

【问题讨论】:

    标签: exception-handling ejb entitymanager rollback


    【解决方案1】:

    JPA 使用事务将实体修改发送到数据库。您可以通过 Bean Managed Transactions (BMT) 手动指定这些事务,或者让应用程序服务器为您完成(容器管理事务;默认)。

    因此,您需要在事务结束时捕获异常,而不是在调用 EntityManager 类的 merge()persist() 方法之后。在您的情况下,当您从最后一个 EJB 对象返回时,事务可能会结束。

    容器管理事务示例(默认):

     @Stateless
     public class OneEjbClass {
          @Inject
          private MyPersistenceEJB persistenceEJB;
    
          public void someMethod() {
               try {
                    persistenceEJB.persistAnEntity();
               } catch(PersistenceException e) {
                    // here you can catch persistence exceptions!
               }
          }
     }
    
     ...
    
     @Stateless
     public class MyPersistenceEJB {
          // this annotation forces application server to create a new  
          // transaction when calling this method, and to commit all 
          // modifications at the end of it!
          @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 
          public void persistAnEntity() {
                // merge stuff with EntityManager
          }
     }
    

    可以指定方法调用(或 EJB 对象的任何方法调用)何时必须、可以或不得创建新事务。这是通过@TransactionAttribute 注释完成的。默认情况下,EJB 的每个方法都配置为 REQUIRED(与指定 @TransactionAttribute(TransactionAttributeType.REQUIRED) 相同),这告诉应用程序重用(继续)调用该方法时处于活动状态的事务,并在需要时创建新事务.

    更多关于交易的信息:http://docs.oracle.com/javaee/7/tutorial/doc/transactions.htm#BNCIH

    更多关于 JPA 和 JTA 的信息在这里:http://en.wikibooks.org/wiki/Java_Persistence/Transactions

    【讨论】:

      猜你喜欢
      • 2010-09-28
      • 2012-05-31
      • 1970-01-01
      • 2016-09-24
      相关资源
      最近更新 更多