Programmatic and Declarative Transaction Management
Programmatic transaction management is a good idea in certain cases where you don't feel the
addition of Spring proxies is worth the trouble or negligible performance loss. Here, you might access
the native transaction yourself and control the transaction manually. A more convenient option that
avoids the overhead of Spring proxies is the TransactionTemplate class, which provides a template
method around which a transactional boundary is started and then committed.
4-1. Problems with Transaction Management
Transaction management is an essential technique in enterprise application development to ensure
data integrity and consistency. Without transaction management, your data and resources may be
corrupted and left in an inconsistent state. Transaction management is particularly important in a
concurrent and distributed environment for recovering from unexpected errors.
In simple words, a transaction is a series of actions that are treated as a single unit of work. These
actions should either complete entirely or take no effect at all. If all the actions go well, the transaction
should be committed permanently. In contrast, if any of them goes wrong, the transaction should be
rolled back to the initial state as if nothing had happened.
The concept of transactions can be described with four key properties: atomicity, consistency,
isolation, and durability (ACID) .
Atomicity : A transaction is an atomic operation that consists of a series of actions. The atomicity of a
transaction ensures that the actions either complete entirely or take no effect at all.
Consistency : Once all actions of a transaction have completed, the transaction is committed. Then
your data and resources will be in a consistent state that conforms to business rules.
Isolation : Because there may be many transactions processing with the same data set at the same
time, each transaction should be isolated from others to prevent data corruption.
Durability : Once a transaction has completed, its result should be durable to survive any system
failure (imagine if the power to your machine was cut right in the middle of a transaction's commit).
Usually, the result of a transaction is written to persistent storage.
To understand the importance of transaction management, let's begin with an example about
purchasing books from an online book shop. First, you have to create a new schema for this application
in your database. If you are choosing Apache Derby as your database engine, you can connect to it with
the JDBC properties shown in Table 4-1. For the examples in this topic, we're using Derby 10.4.2.0.
Table 4-1. JDBC Properties for Connecting to the Application Database
jdbc: derby://localhost:1527/bookshop; create=true