Spring Study Notes - Copyright © 2010 Gavin Lasnitzki Index   Notes   Objectives
Transaction Management

9. Transaction management

9.1. Introduction Key

Objectives: 4.1 Why use Transactions?

Transaction Review

A transaction is an abstraction that is used to group together a series of operations.
The term used to describe whether the operations succeed together or not at all is called atomicity.

A transaction that meets all of the following requirements is said to be an ACID transaction:

  • Atomicity: All of the operations in a transaction are successful or none of them are. The success of every individual operation is tied to the success of the entire group.
  • Consistency: The resulting state at the end of the transaction adheres to a set of rules that define acceptability of the data. The data in the entire system is legal or valid with respect to the rest of the data in the system.
  • Isolation: Changes made within a transaction are visible only to the transaction that is making the changes. Once a transaction commits the changes they are atomically visible to other transactions.
  • Durability: The changes made within a transaction endure beyond the completion of the transaction.

Not using transactions can result in: partial failures (inconsistent data), dirty reads, lost updates

Benefits Key
One of the most compelling reasons to use the Spring Framework is the comprehensive transaction support.
The consistent abstraction for transaction management offers the following benefits:

  • Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
  • Supports declarative transaction management.
  • Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
  • Integrates very well with Spring's various data access abstractions.

9.2. Motivations Key

Objectives: 4.2 Local Transaction Management , 4.3 Programmatic JTA

No application server is needed if you want have declarative transactions (via EJB).
Allows you to choose when to scale up to a full-blown application server.

Traditionally, J2EE developers have had two choices for transaction management: global or local transactions.

Global Transactions Question

  • (Con) Code needs to use JTA (which is cumbersome to use and needs JNDI). Provides access to the UserTransaction.
  • (Con) Code can not be reused outside the application server environment (i.e. in desktop environments).
  • (Con) Normally used via EJB Container Managed Transaction (CMT).
  • (Pro) Gobal transactions provide the ability to work with multiple transactional resources (multiple databases, JMS, etc).

Local Transactions Question

  • (Pro) Easier to use.
  • (Con) Cannot work across multiple transactional resources.
  • (Con) Normally has an invasive to the programming model.

9.3. Key abstractions

Objectives: 4.5 Spring Transaction Management

Notion of a transaction strategy (PlatformTransactionManager interface)
Easily stubbed or mocked.
Throw unchecked exceptions.

The TransactionDefinition interface specifies:

  • Isolation: the degree of isolation this transaction has from the work of other transactions
  • Propagation: normally all code executed within a transaction scope will run in that transaction.
  • Timeout: how long this transaction may run before timing out
  • Read-only status: a read-only transaction does not modify any data.

Non-J2EE Transaction Manager

 

J2EE Transaction Manager
If the DataSource is managed by the JEE container it should be non-transactional as the Spring Framework, rather than the JEE container, will manage transactions.

 

Hibernate Transaction Manager

9.4. Resource synchronization with transactions

9.4.1. High-level approach

The preferred approach is to use Spring's highest level persistence integration APIs: JdbcTemplate, HibernateTemplate, etc

9.4.2. Low-level approach

At a lower level exist classes such as DataSourceUtils (for JDBC), SessionFactoryUtils (for Hibernate).

9.4.3. TransactionAwareDataSourceProxy

At the very lowest level exists the TransactionAwareDataSourceProxy class.
This is a proxy for a target DataSource, which wraps the target DataSource to add awareness of Spring-managed transactions.

9.5. Declarative transaction management

Objectives: 4.4 Declarative Transactions

Made possible with Spring AOP.

EJB CMT vs Spring Transaction Management Key
Both allow you to specify transaction behavior (or lack of it) down to individual method level.

Spring Transaction Management has the following: Question

  • (Pro) Spring Txn works in any environment (and is not tied to JPA).
  • (Pro) Declarative transaction management can be applied to any class (and not just EJBs).
  • (Pro) The Spring Framework offers declarative rollback rules.
  • (Pro) Provides an opportunity to customize transactional behavior, using AOP.
  • (Con) Does not support propagation of transaction contexts across remote calls (as do high-end application servers).

9.5.1. Understanding the Spring Framework's declarative transaction implementation

Declarative transaction support are that this support is enabled via AOP proxies.
Transactional advice is driven by metadata (currently XML- or annotation-based).
The combination of AOP with transactional metadata yields an AOP proxy that uses a TransactionInterceptor in conjunction with an appropriate PlatformTransactionManager implementation to drive transactions around method invocations.

9.5.2. A first example

You can omit the 'transaction-manager' attribute if the bean name of the PlatformTransactionManager is "transactionManager".
The <aop:config/> definition ensures that the transactional advice defined by the 'txAdvice' bean actually executes.

9.5.3. Rolling back

The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.
By default, only unchecked exceptions will cause the transaction to be rolled back.

Rollback can be indicated programmatically (using TransactionStatus#setRollbackOnly()) .

9.5.4. Configuring different transactional semantics for different beans

9.5.5. <tx:advice/> settings Key

Attribute Required? Default Description
name Yes  

The method name(s) with which the transaction attributes are to be associated. The wildcard (*) character can be used to associate the same transaction attribute settings with a number of methods; for example, 'get*', 'handle*', 'on*Event', and so forth.

propagation No REQUIRED The transaction propagation behavior
isolation No DEFAULT The transaction isolation level
timeout No -1 The transaction timeout value (in seconds)
read-only No false Is this transaction read-only?
rollback-for No  

The Exception(s) that will trigger rollback; comma-delimited. For example, 'com.foo.MyBusinessException,ServletException'

no-rollback-for No  

The Exception(s) that will not trigger rollback; comma-delimited. For example, 'com.foo.MyBusinessException,ServletException'

9.5.6. Using @Transactional Key

Transaction configuration via annotations.
@Transactional annotation should only be applied to methods with public visibility.
<tx:annotation-driven/> only looks for @Transactional on beans in the same application context it is defined in.

Attribute Default Description
transaction-manager transactionManager

The name of transaction manager to use.

mode proxy

The default mode "proxy" will process annotated beans to be proxied using Spring's AOP framework. The alternative mode "aspectj" will instead weave the affected classes with Spring's AspectJ transaction aspect.

proxy-target-class false

Applies to proxy mode only. Controls what type of transactional proxies are created for classes annotated with the @Transactional annotation. If "proxy-target-class" attribute is set to "true", then class-based proxies will be created. If "proxy-target-class" is "false" or if the attribute is omitted, then standard JDK interface-based proxies will be created.

order Ordered.LOWEST_PRECEDENCE

Defines the order of the transaction advice that will be applied to beans annotated with @Transactional.

9.5.6.1. @Transactional settings

Property Type Description
propagation enum: Propagation optional propagation setting
isolation enum: Isolation optional isolation level
readOnly boolean read/write vs. read-only transaction
timeout int (in seconds granularity) the transaction timeout
rollbackFor an array of Class objects, which must be derived from Throwable an optional array of exception classes which must cause rollback
rollbackForClassname an array of class names. Classes must be derived from Throwable an optional array of names of exception classes that must cause rollback
noRollbackFor an array of Class objects, which must be derived from Throwable an optional array of exception classes that must not cause rollback.
noRollbackForClassname an array of String class names, which must be derived from Throwable an optional array of names of exception classes that must not cause rollback

 

9.5.7. Transaction propagation Key

Objectives: 4.6 Transaction Propagation Question

  • MANDATORY - Support a current transaction, throw an exception if none exists.
  • NESTED - Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
  • NEVER - Execute non-transactionally, throw an exception if a transaction exists.
  • NOT_SUPPORTED - Execute non-transactionally, suspend the current transaction if one exists.
  • REQUIRED - Support a current transaction, create a new one if none exists.
  • REQUIRES_NEW - Create a new transaction, suspend the current transaction if one exists.
  • SUPPORTS - Support a current transaction, execute non-transactionally if none exists.

 

9.5.7.1. Required

Each such logical transaction scope can individually decide on rollback-only status, with an outer transaction scope being logically independent from the inner transaction scope.
If an inner transaction scopes sets the rollback-only marker, an UnexpectedRollbackException will be thrown (as the outer transaction scope would be unaware of the rollback).

9.5.7.2. RequiresNew

Completely independent transaction are used for each affected transaction scope.
Create a new transaction, suspend the current transaction if one exists. Question

9.5.7.3. Nested

A single physical transaction with multiple savepoints is used (typically mapped to JDBC savepoints)

9.5.8. Advising transactional operations

9.5.9. Using @Transactional with AspectJ

9.6. Programmatic transaction management

9.6.1. Using the TransactionTemplate

Callback approach that frees the application code from having to do the boilerplate acquisition and release of transactional resources, and results in code that is intention driven.

Implement either TransactionCallback() or TransactionCallbackWithoutResult().

Instances of the TransactionTemplate class are threadsafe, but maintain configuration state (like isolation level, etc)

9.6.1.1. Specifying transaction settings

9.6.2. Using the PlatformTransactionManager

The org.springframework.transaction.PlatformTransactionManager can be used directly to manage Transaction management your transaction.

9.7. Choosing between programmatic and declarative transaction management

Declarative transaction management keeps transaction management out of business logic.

9.8. Application server-specific integration

9.8.1. IBM WebSphere

9.8.2. BEA WebLogic

9.8.3. Oracle OC4J

9.9. Solutions to common problems

9.9.1. Use of the wrong transaction manager for a specific DataSource

9.10. Further Resources