What is the impact of explicitly start and commit a transaction while transaction-type is JTA?

user771221 :

I'm working on a J2EE application that will be deployed on Weblogic, is contains two layers:

  1. Business: DAOs and logic methods
  2. EJB: which will use the Business layer

I'm separating the two-layer to be able to reuse the Business layer (as a jar lib) in a Java SE project.

I'm using transaction-type = JTA to let the server manage transactions, but in SE project I'm using transaction-type = RESOURCE_LOCAL so I need to explicitly begin and commit the transaction.

So the question is: Is there any problem if I start and commit transaction explicitly while using JTA?

In other words is there any huge differences between the two below codes:

public void create(T entity) {

    entityManager.persist(entity);

}

and

public void create(T entity) {

    entityManager.getTransaction().begin(); 
    entityManager.persist(entity);
    entityManager.getTransaction().commit();

}
Maciej Kowalski :

You should just be more cautious when dealing with transactions manually. Always have a safety net in case of an exception in order to rollback your operations:

      try {
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        try {
            entityManager.persist(entity);
            transaction.commit();
        } catch (Exception e) {                
            transaction.rollback(); 
            throw e; // optional if you want to manage the exception higher up                         
        } finally {
          entityManager.close(); // optional if you also manage you EM creation manually.
         } 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158152&siteId=1