Skip to content

SR – Chapter 8

April 29, 2010
tags:

Transaction Management
————————–
ACID: Atomicity, Consistency, Isolation, Durability.

Atomicity: Done or not done – not in between.
Consistency: Data right in place after commit.
Isolation: Done alone
Durability: persists after done.

PlatformTransactionManager. general interface.
For single datasource: DataSourceTransactionManager
For JTA in JEE: use JtaTransactionManager (Application server).
For Hib: HibernateTransactionManager
For JPA: JpaTransactionManager.

Example:

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

As all exceptions thrown by the Spring JDBC template are subclasses
of DataAccessException, you ask the transactionmanager to roll back the transaction when this kind of exception is

caught

So to use TM:
1. tm.getTransaction(new DefaultTransactionDefinition();); //tm starts
2. tm.commit/ tm.rollback
3. Configure tm injection in class based on need.

To use TransactionTemplate:
org.springframework.transaction.support.TransactionTemplate

tt = new TransactionTemplate(transactionManager);

tt.execute(new TransactionCallbackWithoutResult()

For those that return results – implement the TransactionCallback interface instead. The return value of the

callback object will finally be returned by the template’s execute()

================================================

TM & Spring 1.X – > AOP used.
———————
1. Configuration: target book,
org.springframework.transaction.interceptor.TransactionProxyFactoryBean
tm, transAttributes(method names, transaction type) map

TM & Spring 2.X – > AOP Advice used.
———————
1. Configuration : & Schema :http://www.springframework.org/schema/tx and aop

Spring Transaction Story

Global Tx:
————-
JTA – is used at the level of application server when you need to manage multiple datasources as well as

integrations with JMS/JCA/. Not needed for single data source connection pooling. ~~ Global Transactions.
JTA only used with JNDI – mostly needs app server.

Local Tx:
————-
Code that manages transactions using a JDBC connection cannot run within a global JTA transaction

Spring helps – 1 code and difft Tx env (local/global) no code change!.

Since this mechanism is based on proxies, only ‘external’ method calls coming in through the proxy will be

intercepted. This means that ‘self-invocation’, i.e. a method within the target object calling some other method

of the target object, won’t lead to an actual transaction at runtime even if the invoked method is marked with

@Transactional

Tx Defn: Isolation, Propagation,Timeout, Readonly status of Tx.
TxStatus : isTx, isRollback, setRollback
JTA Usage in spring: jee:jndi-lookup id=”dataSource” jndi-name=”jdbc/jpetstore”
bean id=”txManager” class=”org.springframework.transaction.jta.JtaTransactionManager”

Caller -> TxProxy -> CustomProxy -> ActualTarget

hibTxMgr->sessionFactory->Datasource
Use the utils class (low level) or the Template class (high level approach).

=============================================

You need to define configuration tags tx:Advice and aop:Config

tx:Advice–> defines which method the transaction has to be applied and what type of Tx.
aop:Config –> Defines the right pointcuts – packages/classes where this has to be applied.

tx:advice id=”txAdvice” transaction-manager=”txManager”>

One aop:config ONLY ::: with different tx’s id.

Above config results in the creation of a transactional proxy around the object that is created from the

‘fooService’ bean definition. The proxy will be configured with the transactional advice, so that when an

appropriate method is invoked on the proxy, a transaction may be started, suspended, be marked as read-only, etc.,

depending on the transaction. configuration associated with that method.

Rollback for a specific exception:
tx:method name=”get*” read-only=”false” rollback-for=”NoProductInStockException
OR
Programmatically — TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()

==========================
Default tx:Advice settings are the follows:
—————————–
1.propagation setting is REQUIRED
2.The isolation level is DEFAULT
3.The transaction is read/write
4,The transaction timeout defaults to the default timeout of the underlying transaction system, or or none if

timeouts are not supported
5. Any RuntimeException will trigger rollback, and any checked Exception will not

============================

Annotation added Tx is simpler:
1. Add configuration

2. @Transactional

——————

To keep advise and Tx AOP together – simple aop around Tx:

<aop:config>
        
        <aop:pointcut id="entryPointMethod" expression="execution(* x.y..*Service.*(..))"/>

        <!-- will execute after the profiling advice (c.f. the order attribute) -->
        <aop:advisor
                advice-ref="txAdvice"
                pointcut-ref="entryPointMethod"
                order="2"/> <!-- order value is higher than the profiling aspect -->

        <aop:aspect id="profilingAspect" ref="profiler">
            <aop:pointcut id="serviceMethodWithReturnValue"
                          expression="execution(!void x.y..*Service.*(..))"/>
            <aop:around method="profile" pointcut-ref="serviceMethodWithReturnValue"/>
        </aop:aspect>

    </aop:config>

Propogation Types: Required,Mandatory,Requires_New,Supports,Not_Supported(Exception thrown),Mandatory,Never

(Existing suspended),Nested.

Code: DefaultTransactionDefinition def/ TransactionDefinition.PROPAGATION_REQUIRES_NEW
XML : propagation=”REQUIRES_NEW”

ISOLATION LEVELS IN Tx.
=========================
DEFAULT: read committed
READ_UNCOMMITTED: all 3 probs
READ_COMMITTED: 2&3 problems
REPEATABLE_READ: problem 3 exists
SERIALIZABLE : No problem
———————
1.Dirty Read: not yet committed data
2.Non-repeatable read: Second time updated FIELD
3.Phantom read: Newly inserted rows in table.

@Transactional(
propagation = Propagation.REQUIRES_NEW,
isolation = Isolation.REPEATABLE_READ,
rollbackFor = IOException.class,
timeout = 30,
readOnly = true,
noRollbackFor = ArithmeticException.class)

Programmatically change rollback:RuleBasedTransactionAttribute attr ;
attr.getRollbackRules().add(new NoRollbackRuleAttribute(TestExcpn.class));
=============================================

Non Spring Tx MANAGEMENT
—————————————-
For domain objects, non spring – Tx mgmt make
1. Domain @Configurable
2. Enable lTWeaving through configuration
3. Enable Tx configurations and Aop.

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: