11.7.6. Roll Back a Transaction


This procedure shows how to roll back 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 roll it back. For information on how to begin a transaction, refer to Section 11.7.3, “Begin a Transaction”.

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

    When you call the rollback() method on the UserTransaction, the Transaction Manager attempts to roll back the transaction and return the data to its previous state.
     
    @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 roll back the transaction.

    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 transaction is rolled back by the Transaction Manager.

Note

Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.