Transaction

Transaction:

  • In software, all-or-nothing operations are called transactions.
  • Transactions allow you to group several operations into a single unit-of-work that either fully happens or fully doesn’t happen.

ACID:

  • Atomic:
    Transactions are made up of one or more activities bundled together as a single unit of work. Atomicity ensures that all of the operations in the transaction happen or that none of them happen.
  • Consistent:
    Once a transaction ends (whether successful or not), the system is left in a state that is consistent with the business that it models.
  • Isolated:
    Transactions should allow multiple users to work with the same data, without each user’s work getting tangled up with the others. Therefore, transactions should be isolated from each other, preventing concurrent reads and writes to the same data from occurring.
  • Durable:
    Once the transaction has completed, the results of the transaction should be made permanent so that they will survive any sort of system crash. This typically involves storing the results in a database or some other form of persistent storage.

Spring’s transaction management support:

  • Programmatic transaction management:
    Programmatic transaction management affords you flexibility in precisely defining transaction boundaries in your code.
public void enrollStudentInCourse() {
	transactionTemplate.execute(
		new TransactionCallback() {
			public Object doInTransaction(TransactionStatus ts) {
				try {
					// do stuff
				} catch (Exception e) {
					ts.setRollbackOnly();
				}
				return null;
			}
		}
	);
}
  • Declarative transaction management:
    Declarative transactions help you decouple an operation from its transaction rules. Spring’s support for declarative transaction management is implemented through Spring’s AOP framework.

Choosing between programmatic and declarative transaction management:

  • When you program transactions into your code, you gain precise control over transaction boundaries, beginning and ending them precisely where you want.
  • Typically, you will not require the fine-grained control offered by programmatic transactions and will choose to declare your transactions in the context definition file.

(Source: Spring in Action)

留言