10.7.3. Begin a Transaction

This procedure shows how to begin a new JTA transaction, or how to participate in a distributed transaction using the Java Transaction Service (JTS) protocol.
Distributed Transactions

A distributed transaction is one where the transaction participants are in separate applications on multiple servers. If a participant joins a transaction that already exists, rather than creating a new transaction context, the two (or more) participants which share the context are participating a distributed transaction. In order to use distribured transactions, you must configure the ORB. Refer to Refer to the ORB Configuration section of the Administration and Configuration Guide for more information on ORB configuration.

  1. Get an instance of UserTransaction.

    You can get the instance using JNDI, injection, or an EJB's EjbContext, if the EJB uses bean-managed transactions, by means of a @TransactionManagement(TransactionManagementType.BEAN) annotation.
    • JNDI

      new InitialContext().lookup("java:comp/UserTransaction")
    • Injection

      @Resource UserTransaction userTransaction;
    • EjbContext

  2. Call UserTransaction.begin() after you connect to your datasource.

    try {
        System.out.println("\nCreating connection to database: "+url);
        stmt = conn.createStatement();  // non-tx statement
        try {
            System.out.println("Starting top-level transaction.");
            stmtx = conn.createStatement(); // will be a tx-statement
Participate in an existing transaction using the JTS API.

One of the benefits of EJBs is that the container manages all of the transactions. If you have set up the ORB, the container will manage distributed transactions for you.


The transaction begins. All uses of your datasource until you commit or roll back the transaction are transactional.