質問

I have an Entity Manager in my EJB

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

I populate an object and then I commit it in my DB, but if I have an exception, for duplicate ID, I can't catch it and I don't know why.

    try{
      em.merge(boelLog);
    } catch (Exception e){
        System.out.println("Generic Exception");
    }
役に立ちましたか?

解決

JPA uses transactions to send entity modifications to the database. You can specify those transactions manually through Bean Managed Transactions (BMT) or let the application server do it for you (Container Managed Transactions; the default).

So, you need to catch the exception at the end of the transaction, and not after calling merge() or persist() methods of EntityManager class. In your case, probably the transaction will end when you return from the last EJB object.

Example for Container Managed Transactions (the default):

 @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
      }
 }

It's possible to specify when a method call (or any method call of an object of an EJB) must, can or must not create a new transaction. This is done through the @TransactionAttribute annotation. By default, every method of an EJB is configured as REQUIRED (same as specifying @TransactionAttribute(TransactionAttributeType.REQUIRED)), that tells the application to reuse (continue) the transaction that is active when that method was called, and create a new transaction if needed.

More about transactions here: http://docs.oracle.com/javaee/7/tutorial/doc/transactions.htm#BNCIH

More about JPA and JTA here: http://en.wikibooks.org/wiki/Java_Persistence/Transactions

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top