Wednesday, May 18, 2011

Transactions

Motivated by two independent requirements:
  • Cuncurrent database access
  • Resilience to system failures
A transaction is a sequence of one or more SQL operations treated as a unit.

ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee database transactions are processed reliably. In the context of databases, a single logical operation on the data is called a transaction. For example, a transfer of funds from one bank account to another, even though that might involve multiple changes (such as debiting one account and crediting another), is a single transaction.


Atomic
   Each unit of work is an all or nothing operation. (logging)
Consistent
   Database integrity constraints are never violated.
   It ensures the truthfulness of the database.
Isolated
   Isolating transactions from each other.
   Serializability - Operations may be interleaved, but execution must be equivalent to some sequential (serial) order of all transactions.
Durable
   Committed changes are permanent.
   (If system crashes after transaction commits, all effects of transaction remain in database.)


IMPLEMENTING
in class:
   @Transactional
(uses "transactionManager" by default)

By default, a transaction is rolled back if a RuntimeException has been thrown!
Default settings can be overridden with rollbackFor/noRollbackFor attributes.
After checked exception occurs transaction is commited.

in config file (xml):

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>
(Instructs the container to look for beans with @Transactional and decorate them)


Using transactions when only reading data allows Spring to optimize the transaction resources
e.g. 2 sql will be executed in 1 connection, prevents Hibernate from flushing its session, Oracle accepts only SELECT statements

No comments:

Post a Comment