Transactions

A transaction is a group of several operations that must behave atomically (i.e., as if they are a single, indivisible operation). With regard to databases, transactions allow you to combine one or more database actions into a single atomic unit. If you have an application that needs to execute multiple SQL statements to fulfill one goal (say an inventory management system that needs to move items from an INVENTORY table to a SHIPPING table), you probably want to use JDBC’s transaction services to accomplish the goal.

This section gives a brief overview of transactions with respect to relational databases and JDBC. For broader coverage of transactions in the general J2EE environment, see Chapter 16.

Working with a transaction involves the following steps: start the transaction, perform its component operations, and then either commit the transaction if all the component operations succeed or roll it back if one of the operations fails. The ability to roll back a transaction is the key feature. This means that if any one SQL statement fails, the entire operation fails, and it is as though none of the component operations took place. Therefore, it is impossible to end up with a situation in which, for example, the INVENTORY table has been debited, but the SHIPPING table has not been credited.

Another issue with transactions and databases concerns changes to the database becoming visible to the rest of the system. Transactions can operate at varying levels ...

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.