10.7.5. Commit a Transaction

This procedure shows how to commit a transaction using the Java Transaction API (JTA). This API is used for both local transactions and distributed transactions. Distributed transactions are managed by the Java Transaction Server (JTS) and require configuration of an Object Request Broker (ORB). For more information on ORB configuration, refer to the ORB Configuration section of the Administration and Configuration Guide.
Prerequisites

You must begin a transaction before you can commit it. For information on how to begin a transaction, refer to Section 10.7.3, “Begin a Transaction”.

  1. Call the commit() method on the UserTransaction.

    When you call the commit() method on the UserTransaction, the Transaction Manager attempts to commit the transaction.
    @Inject
    private UserTransaction userTransaction;
    
    public void updateTable(String key, String value)
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            userTransaction.begin():
            <!-- Perform some data manipulation using entityManager -->
    			  ...
    			  // Commit the transaction
            userTransaction.commit();
        } catch (Exception ex) {
            <!-- Log message or notify Web page -->
            ...
            try {
                userTransaction.rollback();
            } catch (SystemException se) {
                throw new RuntimeException(se);
            }
            throw new RuntimeException(e);
        } finally {
            entityManager.close();
        }
    }
    
    
  2. If you use Container Managed Transactions (CMT), you do not need to manually commit.

    If you configure your bean to use Container Managed Transactions, the container will manage the transaction lifecycle for you based on annotations you configure in the code.
Result

Your datasource commits and your transaction ends, or an exception is thrown.

Note