Exception not cuaght with Entity Manager

后端 未结 1 1126
旧时难觅i
旧时难觅i 2021-01-26 01:22

I have an Entity Manager in my EJB

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

I populate an object and then I

1条回答
  •  旧巷少年郎
    2021-01-26 01:49

    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

    0 讨论(0)
提交回复
热议问题