Skip navigation.
Downloads | Product Documentation | Support

Programming WebLogic JTA

# Introducing Transactions

This section discusses the following topics:

- Overview of Transactions in WebLogic Server Applications
- When to Use Transactions
- What Happens During a Transaction
- Transactions Sample Code

# Overview of Transactions in WebLogic Server Applications

This section includes the following sections:

- ACID Properties of Transactions
- Supported Programming Model
- Supported API Models
- Distributed Transactions and the Two-Phase Commit Protocol
- Support for Business Transactions

## ACID Properties of Transactions

One of the most fundamental features of WebLogic Server is transaction management. Transactions are a means to guarantee that database changes are completed accurately and that they take on all the ACID properties of a high-performance transaction, including:

- Atomicity—all changes that a transaction makes to a database are made as one unit; otherwise, all changes are rolled back.
- Consistency—a successful transaction transforms a database from a previous valid state to a new valid state.
- Isolation—changes that a transaction makes to a database are not visible to other operations until the transaction completes its work.
- Durability—changes that a transaction makes to a database survive future system or media failures.

WebLogic Server protects the integrity of your transactions by providing a complete infrastructure for ensuring that database updates are done accurately, even across a variety of resource managers. If any one of the operations fails, the entire set of operations is rolled back.

## Supported Programming Model

WebLogic Server supports transactions in the Sun Microsystems, Inc., JavaTM 2, Enterprise Edition (J2EE) programming model. WebLogic Server provides full support for transactions in Java applications that use Enterprise JavaBeans, in compliance with the Enterprise JavaBeans Specification 2.0, published by Sun Microsystems, Inc. WebLogic Server also supports the Java Transaction API (JTA) Specification 1.0.1a, also published by Sun Microsystems, Inc.

## Supported API Models

WebLogic Server supports the Sun Microsystems, Inc. Java Transaction API (JTA), which is used by:

- Enterprise JavaBean (EJB) applications within the WebLogic Server EJB container.
- Remote Method Invocation (RMI) applications within the WebLogic Server infrastructure.

For information about JTA, see the following sources:

- The javax.transaction and javax.transaction.xa package APIs.
- The Java Transaction API specification, published by Sun Microsystems, Inc.

## Distributed Transactions and the Two-Phase Commit Protocol

WebLogic Server supports distributed transactions and the two-phase commit protocol for enterprise applications. A distributed transaction is a transaction that updates multiple resource managers (such as databases) in a coordinated manner. In contrast, a local transaction begins and commits the transaction to a single resource manager that internally coordinates API calls; there is no transaction manager. The two-phase commit protocol is a method of coordinating a single transaction across two or more resource managers. It guarantees data integrity by ensuring that transactional updates are committed in all of the participating databases, or are fully rolled back out of all the databases, reverting to the state prior to the start of the transaction. In other words, either all the participating databases are updated, or none of them are updated.

Distributed transactions involve the following participants:

- Transaction originator—initiates the transaction. The transaction originator can be a user application, an Enterprise JavaBean, or a JMS client.
- Transaction manager—manages transactions on behalf of application programs. A transaction manager coordinates commands from application programs to start and complete transactions by communicating with all resource managers that are participating in those transactions. When resource managers fail during transactions, transaction managers help resource managers decide whether to commit or roll back pending transactions.
- Recoverable resource—provides persistent storage for data. The resource is most often a database.
- Resource manager—provides access to a collection of information and processes. Transaction-aware JDBC drivers are common resource managers. Resource managers provide transaction capabilities and permanence of actions; they are entities accessed and controlled within a distributed transaction. The communication between a resource manager and a specific resource is called a transaction branch.

The first phase of the two-phase commit protocol is called the prepare phase. The required updates are recorded in a transaction log file, and the resource must indicate, through a resource manager, that it is ready to make the changes. Resources can either vote to commit the updates or to roll back to the previous state. What happens in the second phase depends on how the resources vote. If all resources vote to commit, all the resources participating in the transaction are updated. If one or more of the resources vote to roll back, then all the resources participating in the transaction are rolled back to their previous state.

## Support for Business Transactions

WebLogic JTA provides the following support for your business transactions:

- Creates a unique transaction identifier when a client application initiates a transaction.
- Supports an optional transaction name describing the business process that the transaction represents. The transaction name makes statistics and error messages more meaningful.
- Works with the WebLogic Server infrastructure to track objects that are involved in a transaction and, therefore, need to be coordinated when the transaction is ready to commit.
- Notifies the resource managers—which are, most often, databases—when they are accessed on behalf of a transaction. Resource managers then lock the accessed records until the end of the transaction.
- Orchestrates the two-phase commit when the transaction completes, which ensures that all the participants in the transaction commit their updates simultaneously. It coordinates the commit with any databases that are being updated using Open Group's XA protocol. Many popular relational databases support this standard.
- Executes the rollback procedure when the transaction must be stopped.
- Executes a recovery procedure when failures occur. It determines which transactions were active in the machine at the time of the crash, and then determines whether the transaction should be rolled back or committed.
- Manages transaction timeouts. If a business operation takes too much time or is only partially completed due to failures, the system takes action to automatically issue a timeout for the transaction and free resources, such as database locks.

# When to Use Transactions

Transactions are appropriate in the situations described in the following list. Each situation describes a transaction model supported by the WebLogic Server system. Keep in mind that distributed transactions should not span more than a single user input screen; more complex, higher level transactions are best implemented with a series of distributed transactions.

- Within the scope of a single client invocation on an object, the object performs multiple edits to data in a database. If one of the edits fails, the object needs a mechanism to roll back all the edits. (In this situation, the individual database edits are not necessarily EJB or RMI invocations. A client, such as an applet, can obtain a reference to the `Transaction` and `TransactionManager` objects, using JNDI, and start a transaction.)

For example, consider a banking application. The client invokes the transfer operation on a teller object. The transfer operation requires the teller object to make the following invocations on the bank database:

- Invoking the debit method on one account.
- Invoking the credit method on another account.

If the credit invocation on the bank database fails, the banking application needs a way to roll back the previous debit invocation.

- The client application needs a conversation with an object managed by the server application, and the client application needs to make multiple invocations on a specific object instance. The conversation may be characterized by one or more of the following:

- Data is cached in memory or written to a database during or after each successive invocation.
- Data is written to a database at the end of the conversation.
- The client application needs the object to maintain an in-memory context between each invocation; that is, each successive invocation uses the data that is being maintained in memory across the conversation.
- At the end of the conversation, the client application needs the ability to cancel all database write operations that may have occurred during or at the end of the conversation.

# When Not to Use Transactions

Transactions are not always appropriate. For example, if a series of transactions take a long time, implement them with a series of distributed transactions. Here is an example of an incorrect use of transactions.

- The client application needs to make invocations on several objects, which may involve write operations to one or more databases. If any one invocation is unsuccessful, any state that is written (either in memory or, more typically, to a database) must be rolled back.

For example, consider a travel agent application. The client application needs to arrange for a journey to a distant location; for example, from Strasbourg, France, to Alice Springs, Australia. Such a journey would inevitably require multiple individual flight reservations. The client application works by reserving each individual segment of the journey in sequential order; for example, Strasbourg to Paris, Paris to New York, New York to Los Angeles. However, if any individual flight reservation cannot be made, the client application needs a way to cancel all the flight reservations made up to that point.

# What Happens During a Transaction

This topic includes the following sections:

- Transactions in WebLogic Server EJB Applications
- Transactions in WebLogic Server RMI Applications

## Transactions in WebLogic Server EJB Applications

Figure 1-1 illustrates how transactions work in a WebLogic Server EJB application.

Figure 1-1 How Transactions Work in a WebLogic Server EJB Application

WebLogic Server supports two types of transactions in WebLogic Server EJB applications:

- In container-managed transactions, the WebLogic Server EJB container manages the transaction demarcation. Transaction attributes in the EJB deployment descriptor determine how the WebLogic Server EJB container handles transactions with each method invocation. For more information about the deployment descriptor, see Programming WebLogic EJB.
- In bean-managed transactions, the EJB manages the transaction demarcation. The EJB makes explicit method invocations on the `UserTransaction` object to begin, commit, and roll back transactions. For more information about the `UserTransaction` object, see the WebLogic Server Javadoc.

The sequence of transaction events differs between container-managed and bean-managed transactions.

### Container-managed Transactions

For EJB applications with container-managed transactions, a basic transaction works in the following way:

1. In the EJB's deployment descriptor, the Bean Provider or Application Assembler specifies the transaction type (`transaction-type` element) for container-managed demarcation (`Container`).
2. In the EJB's deployment descriptor, the Bean Provider or Application Assembler specifies the default transaction attribute (`trans-attribute` element) for the EJB, which is one of the following settings: `NotSupported`, `Required`, `Supports`, `RequiresNew`, `Mandatory`, or `Never`. For a detailed description of these settings, see Section 17.6.2 in the Enterprise JavaBeans Specification 2.0, published by Sun Microsystems, Inc.
3. Optionally, in the EJB's deployment descriptor, the Bean Provider or Application Assembler specifies the `trans-attribute` for one or more methods.
4. When a client application invokes a method in the EJB, the EJB container checks the `trans-attribute` setting in the deployment descriptor for that method. If no setting is specified for the method, the EJB uses the default `trans-attribute` setting for that EJB.
5. The EJB container takes the appropriate action depending on the applicable `trans-attribute` setting.

- For example, if the `trans-attribute` setting is `Required`, the EJB container invokes the method within the existing transaction context or, if the client called without a transaction context, the EJB container begins a new transaction before executing the method.
- In another example, if the `trans-attribute` setting is `Mandatory`, the EJB container invokes the method within the existing transaction context. If the client called without a transaction context, the EJB container throws the `javax.transaction.TransactionRequiredException` exception.

6. During invocation of the business method, if it is determined that a rollback is required, the business method calls the `EJBContext.setRollbackOnly` method, which notifies the EJB container that the transaction is to be rolled back at the end of the method invocation.

Note: Calling the `EJBContext.setRollbackOnly` method is allowed only for methods that have a meaningful transaction context.

7. At the end of the method execution and before the result is sent to the client, the EJB container completes the transaction, either by committing the transaction or rolling it back (if the `EJBContext.setRollbackOnly` method was called).

You can control transaction timeouts by setting the Timeout Seconds attribute using the Administration Console. See the Administration Console Online Help.

### Bean-managed Transactions

For EJB applications with bean-managed transaction demarcations, a basic transaction works in the following way:

1. In the EJB's deployment descriptor, the Bean Provider or Application Assembler specifies the transaction type (`transaction-type` element) for container-managed demarcation (`Bean`).
2. The client application uses JNDI to obtain an object reference to the `UserTransaction` object for the WebLogic Server domain.
3. The client application begins a transaction using the `UserTransaction.begin` method, and issues a request to the EJB through the EJB container. All operations on the EJB execute within the scope of a transaction.

- If a call to any of these operations raises an exception (either explicitly or as a result of a communication failure), the exception can be caught and the transaction can be rolled back using the `UserTransaction.rollback` method.
- If no exceptions occur, the client application commits the current transaction using the `UserTransaction.commit` method. This method ends the transaction and starts the processing of the operation. The transaction is committed only if all of the participants in the transaction agree to commit.

4. The `UserTransaction.commit` method causes the EJB container to call the transaction manager to complete the transaction.
5. The transaction manager is responsible for coordinating with the resource managers to update any databases.

## Transactions in WebLogic Server RMI Applications

Figure 1-2 illustrates how transactions work in a WebLogic Server RMI application.

Figure 1-2 How Transactions Work in a WebLogic Server RMI Application

For RMI client and server applications, a basic transaction works in the following way:

1. The application uses JNDI to return an object reference to the `UserTransaction` object for the WebLogic Server domain.

Obtaining the object reference begins a conversational state between the application and that object. The conversational state continues until the transaction is completed (committed or rolled back). Once instantiated, RMI objects remain active in memory until they are released (typically during server shutdown). For the duration of the transaction, the WebLogic Server infrastructure does not perform any deactivation or activation.

2. The client application begins a transaction using the `UserTransaction.begin` method, and issues a request to the server application. All operations on the server application execute within the scope of a transaction.

- If a call to any of these operations raises an exception (either explicitly or as a result of a communication failure), the exception can be caught and the transaction can be rolled back using the `UserTransaction.rollback` method.
- If no exceptions occur, the client application commits the current transaction using the `UserTransaction.commit` method. This method ends the transaction and starts the processing of the operation. The transaction is committed only if all of the participants in the transaction agree to commit.

3. The `UserTransaction.commit` method causes WebLogic Server to call the transaction manager to complete the transaction.
4. The transaction manager is responsible for coordinating with the resource managers to update any databases.

For more information, see Transactions in RMI Applications.

# Transactions Sample Code

This section includes the following sections:

- Transactions Sample EJB Code
- Transactions Sample RMI Code

## Transactions Sample EJB Code

This section provides a walkthrough of sample code fragments from a class in an EJB application. This topic includes the following sections:

- Importing Packages
- Using JNDI to Return an Object Reference
- Starting a Transaction
- Completing a Transaction

The code fragments demonstrate using the `UserTransaction` object for bean-managed transaction demarcation. The deployment descriptor for this bean specifies the transaction type (`transaction-type` element) for transaction demarcation (`Bean`).

Notes: In a global transaction, use a database connection from a local TxDataSource—on the WebLogic Server instance on which the EJB is running. Do not use a connection from a TxDataSource on a remote WebLogic Server instance.

These code fragments do not derive from any of the sample applications that ship with WebLogic Server. They merely illustrate the use of the `UserTransaction` object within an EJB application.

### Importing Packages

Listing 1-1 shows importing the necessary packages for transactions, including:

- `javax.transaction.UserTransaction`. For a list of methods associated with this object, see the online Javadoc.
- System exceptions. For a list of exceptions, see the online Javadoc.

Listing 1-1 Importing Packages

>     import javax.naming.*;
>     import javax.transaction.UserTransaction;
>     import javax.transaction.SystemException;
>     import javax.transaction.HeuristicMixedException
>     import javax.transaction.HeuristicRollbackException
>     import javax.transaction.NotSupportedException
>     import javax.transaction.RollbackException
>     import javax.transaction.IllegalStateException
>     import javax.transaction.SecurityException
>     import java.sql.*;
>     import java.util.*;

### Using JNDI to Return an Object Reference

Listing 1-2 shows how look up an object on the JNDI tree.

Listing 1-2 Performing a JNDI Lookup

>     Context ctx = null;
>     Hashtable env = new Hashtable();

>     env.put(Context.INITIAL_CONTEXT_FACTORY,
>              "weblogic.jndi.WLInitialContextFactory");

>     // Parameters for the WebLogic Server.
>     // Substitute the correct hostname, port number
>     // user name, and password for your environment:
>     env.put(Context.PROVIDER_URL, "t3://localhost:7001");
>     env.put(Context.SECURITY_PRINCIPAL, "Fred");
>     env.put(Context.SECURITY_CREDENTIALS, "secret");

>     ctx = new InitialContext(env);

>     UserTransaction tx = (UserTransaction)
>       ctx.lookup("javax.transaction.UserTransaction");

### Starting a Transaction

Listing 1-3 shows starting a transaction by getting a `UserTransaction` object and calling the `javax.transaction.UserTransaction.begin()` method. Database operations that occur after this method invocation and prior to completing the transaction exist within the scope of this transaction.

Listing 1-3 Starting a Transaction

>     UserTransaction tx = (UserTransaction)
>       ctx.lookup("javax.transaction.UserTransaction");
>     tx.begin();

### Completing a Transaction

Listing 1-4 shows completing the transaction depending on whether an exception was thrown during any of the database operations that were attempted within the scope of this transaction:

- If an exception was thrown during any of the database operations, the application calls the `javax.transaction.UserTransaction.rollback()` method.
- If no exception was thrown, the application calls the `javax.transaction.UserTransaction.commit()` method to attempt to commit the transaction after all database operations completed successfully. Calling this method ends the transaction and starts the processing of the operation, causing the WebLogic Server EJB container to call the transaction manager to complete the transaction. The transaction is committed only if all of the participants in the transaction agree to commit.

Listing 1-4 Completing a Transaction

>     tx.commit();

>     // or:

>     tx.rollback();

## Transactions Sample RMI Code

This topic provides a walkthrough of sample code fragments from a class in an RMI application. This topic includes the following sections:

- Importing Packages
- Using JNDI to Return an Object Reference to the UserTransaction Object
- Starting a Transaction
- Completing a Transaction

The code fragments demonstrate using the `UserTransaction` object for RMI transactions. For guidelines on using transactions in RMI applications, see Transactions in RMI Applications.

Note: These code fragments do not derive from any of the sample applications that ship with WebLogic Server. They merely illustrate the use of the `UserTransaction` object within an RMI application.

### Importing Packages

Listing 1-5 shows importing the necessary packages, including the following packages used to handle transactions:

- `javax.transaction.UserTransaction`. For a list of methods associated with this object, see the online Javadoc.
- System exceptions. For a list of exceptions, see the online Javadoc.

Listing 1-5 Importing Packages

>     import javax.naming.*;
>     import java.rmi.*;
>     import javax.transaction.UserTransaction;
>     import javax.transaction.SystemException;
>     import javax.transaction.HeuristicMixedException
>     import javax.transaction.HeuristicRollbackException
>     import javax.transaction.NotSupportedException
>     import javax.transaction.RollbackException
>     import javax.transaction.IllegalStateException
>     import javax.transaction.SecurityException
>     import java.sql.*;
>     import java.util.*;

After importing these classes, initialize an instance of the `UserTransaction` object to null.

### Using JNDI to Return an Object Reference to the UserTransaction Object

Listing 1-6 shows searching the JNDI tree to return an object reference to the `UserTransaction` object for the appropriate WebLogic Server domain.

Note: Obtaining the object reference begins a conversational state between the application and that object. The conversational state continues until the transaction is completed (committed or rolled back). Once instantiated, RMI objects remain active in memory until they are released (typically during server shutdown). For the duration of the transaction, the WebLogic Server infrastructure does not perform any deactivation or activation.

Listing 1-6 Performing a JNDI Lookup

>     Context ctx = null;
>     Hashtable env = new Hashtable();

>     env.put(Context.INITIAL_CONTEXT_FACTORY,
>              "weblogic.jndi.WLInitialContextFactory");

>     // Parameters for the WebLogic Server.
>     // Substitute the correct hostname, port number
>     // user name, and password for your environment:
>     env.put(Context.PROVIDER_URL, "t3://localhost:7001");
>     env.put(Context.SECURITY_PRINCIPAL, "Fred");
>     env.put(Context.SECURITY_CREDENTIALS, "secret");

>     ctx = new InitialContext(env);

>     UserTransaction tx = (UserTransaction)
>       ctx.lookup("javax.transaction.UserTransaction");

### Starting a Transaction

Listing 1-7 shows starting a transaction by calling the `javax.transaction.UserTransaction.begin()` method. Database operations that occur after this method invocation and prior to completing the transaction exist within the scope of this transaction.

Listing 1-7 Starting a Transaction

>     UserTransaction tx = (UserTransaction)
>       ctx.lookup("javax.transaction.UserTransaction");
>     tx.begin();

### Completing a Transaction

Listing 1-8 shows completing the transaction depending on whether an exception was thrown during any of the database operations that were attempted within the scope of this transaction:

- If an exception was thrown, the application calls the `javax.transaction.UserTransaction.rollback()` method if an exception was thrown during any of the database operations.
- If no exception was thrown, the application calls the `javax.transaction.UserTransaction.commit()` method to attempt to commit the transaction after all database operations completed successfully. Calling this method ends the transaction and starts the processing of the operation, causing WebLogic Server to call the transaction manager to complete the transaction. The transaction is committed only if all of the participants in the transaction agree to commit.

Listing 1-8 Completing a Transaction

>     tx.commit();

>     // or:

>     tx.rollback();