Part - 1 
Spring and Transaction 
Ye Win 
12/08/2014
Contents 
• Who This Slide Is For? 
• Introduction 
• Local Vs Global Transactions 
• Programmatic Vs Declarative 
• Spring Transaction Abstractions 
• Programmatic & Declarative (Practical) 
• Conclusion
• Ps. Slide notes from Spring Transaction 
Abstractions Section are soul for this slide.
Who This Slide Is For? 
• This session will let you know how to manage transactions in Spring. 
You can understand the programmatic as well as declarative 
transaction management in Spring Framework. 
• You can take the source codes of the examples given in this slide 
from links available at 
https://drive.google.com/open?id=0B72s1dEbEPzBLS00M0JNZDd0X 
3c&authuser=0
Introduction 
Transaction management is an important part of and RDBMS oriented enterprise applications to 
ensure data integrity and consistency. The concept of transactions can be described with following four 
key properties described as ACID: 
1. Atomicity: A transaction should be treated as a single unit of operation which means either the entire sequence of 
operations is successful or unsuccessful. 
2. Consistency: This represents the consistency of the referential integrity of the database, unique primary keys in 
tables etc. 
3. Isolation: 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. 
4. Durability: Once a transaction has completed, the results of this transaction have to be made permanent and 
cannot be erased from the database due to system failure. 
Spring framework provides an abstract layer on top of different underlying transaction management 
APIs. Spring supports both programmatic and declarative transaction management and Spring 
transaction management can be implemented without a need of application server.
Local Vs Global Tansactions 
• Local transaction management can be useful in a centralized computing environment where 
application components and resources are located at a single site, and transaction management 
only involves a local data manager running on a single machine. Local transactions are easier to be 
implemented. 
• Global transaction management is required in a distributed computing environment where all the 
resources are distributed across multiple systems. In such a case transaction management needs 
to be done both at local and global levels. A distributed or a global transaction is executed across 
multiple systems, and its execution requires coordination between the global transaction 
management system and all the local data managers of all the involved systems.
Programmatic Vs Declarative 
• Spring supports two types of transaction management: 
1. Programmatic transaction management: This means that you have manage the transaction with the 
help of programming. That gives you extreme flexibility, but it is difficult to maintain. 
2. Declarative transaction management: This means you separate transaction management from the 
business code. You only use annotations or XML based configuration to manage the transactions. 
• Declarative transaction management is preferable over programmatic transaction management 
though it is less flexible than programmatic transaction management, which allows you to control 
transactions through your code. But as a kind of crosscutting concern, declarative transaction 
management can be modularized with the AOP approach. Spring supports declarative transaction 
management through the Spring AOP framework.
Spring Transaction Abstractions 
We have to implements mainly three transaction interface. 
1)org.springframework.transaction.PlatformTransactionManager 
2)org.springframework.transaction.TransactionDefinition 
3)org.springframework.transaction.TransactionStatus
Method Summary 
(1) Interface PlatformTransactionManager 
Modifier and Type Method and Description 
void commit(TransactionStatus status) 
Commit the given transaction, with regard to its status. 
TransactionStatus getTransaction(TransactionDefinition definition) 
Return a currently active transaction or create a new one, according to the specified propagation 
behavior. 
void rollback(TransactionStatus status) 
Perform a rollback of the given transaction.
Fields 
Modifier and Type Field and Description 
static int ISOLATION_DEFAULT 
Use the default isolation level of the underlying datastore. 
Eg. READ COMMITTED is the default isolation level for the Microsoft SQL Server Database Engine. 
static int ISOLATION_READ_COMMITTED 
Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur. 
static int ISOLATION_READ_UNCOMMITTED 
Indicates that dirty reads, non-repeatable reads and phantom reads can occur. 
Field Summary 
(2) Interface TransactionDefinition
(2) Interface TransactionDefinition 
static int ISOLATION_REPEATABLE_READ 
Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can 
occur. 
static int ISOLATION_SERIALIZABLE 
Indicates that dirty reads, non-repeatable reads and phantom reads are prevented. 
static int PROPAGATION_MANDATORY 
Support a current transaction; throw an exception if no current transaction exists.
(2) Interface TransactionDefinition 
static int PROPAGATION_NESTED 
Execute within a nested transaction if a current transaction exists, behave 
like PROPAGATION_REQUIRED else. 
static int PROPAGATION_NEVER 
Do not support a current transaction; throw an exception if a current transaction exists. 
static int PROPAGATION_NOT_SUPPORTED 
Do not support a current transaction; rather always execute non-transactionally. 
static int PROPAGATION_REQUIRED 
Support a current transaction; create a new one if none exists.
(2) Interface TransactionDefinition 
static int PROPAGATION_REQUIRES_NEW 
Create a new transaction, suspending the current transaction if one exists. 
static int PROPAGATION_SUPPORTS 
Support a current transaction; execute non-transactionally if none exists. 
static int TIMEOUT_DEFAULT 
Use the default timeout of the underlying transaction system, or none if timeouts are not supported.
All MethodsInstance MethodsAbstract Methods 
Modifier and Type Method and Description 
int getIsolationLevel() 
Return the isolation level. 
String getName() 
Return the name of this transaction. 
int getPropagationBehavior() 
Return the propagation behavior. 
int getTimeout() 
Return the transaction timeout. 
boolean isReadOnly() 
Return whether to optimize as a read-only transaction. 
Method Summary 
(2) Interface TransactionDefinition
Modifier and Type Method and Description 
void flush() 
Flush the underlying session to the datastore, if applicable: for example, all affected Hibernate/JPA 
sessions. 
boolean hasSavepoint() 
Return whether this transaction internally carries a savepoint, that is, has been created as nested 
transaction based on a savepoint. 
boolean isCompleted() 
Return whether this transaction is completed, that is, whether it has already been committed or rolled 
back. 
boolean isNewTransaction() 
Return whether the present transaction is new (else participating in an existing transaction, or 
potentially not running in an actual transaction in the first place). 
boolean isRollbackOnly() 
Return whether the transaction has been marked as rollback-only (either by the application or by the 
transaction infrastructure). 
void setRollbackOnly() 
Set the transaction rollback-only. 
Method Summary 
(3) Interface TransactionStatus
Conclusion 
• The Spring transaction management mechanism is 
very powerful. 
• It can integrate any persistence framework 
• A future post Part – 2 will explain more details of 
Programmatic and Declarative Transaction.
Do you have Questions ? 
Please Discuss :
Spring Transaction Management

Spring Transaction Management

  • 1.
    Part - 1 Spring and Transaction Ye Win 12/08/2014
  • 2.
    Contents • WhoThis Slide Is For? • Introduction • Local Vs Global Transactions • Programmatic Vs Declarative • Spring Transaction Abstractions • Programmatic & Declarative (Practical) • Conclusion
  • 3.
    • Ps. Slidenotes from Spring Transaction Abstractions Section are soul for this slide.
  • 4.
    Who This SlideIs For? • This session will let you know how to manage transactions in Spring. You can understand the programmatic as well as declarative transaction management in Spring Framework. • You can take the source codes of the examples given in this slide from links available at https://drive.google.com/open?id=0B72s1dEbEPzBLS00M0JNZDd0X 3c&authuser=0
  • 5.
    Introduction Transaction managementis an important part of and RDBMS oriented enterprise applications to ensure data integrity and consistency. The concept of transactions can be described with following four key properties described as ACID: 1. Atomicity: A transaction should be treated as a single unit of operation which means either the entire sequence of operations is successful or unsuccessful. 2. Consistency: This represents the consistency of the referential integrity of the database, unique primary keys in tables etc. 3. Isolation: 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. 4. Durability: Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure. Spring framework provides an abstract layer on top of different underlying transaction management APIs. Spring supports both programmatic and declarative transaction management and Spring transaction management can be implemented without a need of application server.
  • 6.
    Local Vs GlobalTansactions • Local transaction management can be useful in a centralized computing environment where application components and resources are located at a single site, and transaction management only involves a local data manager running on a single machine. Local transactions are easier to be implemented. • Global transaction management is required in a distributed computing environment where all the resources are distributed across multiple systems. In such a case transaction management needs to be done both at local and global levels. A distributed or a global transaction is executed across multiple systems, and its execution requires coordination between the global transaction management system and all the local data managers of all the involved systems.
  • 7.
    Programmatic Vs Declarative • Spring supports two types of transaction management: 1. Programmatic transaction management: This means that you have manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain. 2. Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions. • Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. But as a kind of crosscutting concern, declarative transaction management can be modularized with the AOP approach. Spring supports declarative transaction management through the Spring AOP framework.
  • 8.
    Spring Transaction Abstractions We have to implements mainly three transaction interface. 1)org.springframework.transaction.PlatformTransactionManager 2)org.springframework.transaction.TransactionDefinition 3)org.springframework.transaction.TransactionStatus
  • 9.
    Method Summary (1)Interface PlatformTransactionManager Modifier and Type Method and Description void commit(TransactionStatus status) Commit the given transaction, with regard to its status. TransactionStatus getTransaction(TransactionDefinition definition) Return a currently active transaction or create a new one, according to the specified propagation behavior. void rollback(TransactionStatus status) Perform a rollback of the given transaction.
  • 10.
    Fields Modifier andType Field and Description static int ISOLATION_DEFAULT Use the default isolation level of the underlying datastore. Eg. READ COMMITTED is the default isolation level for the Microsoft SQL Server Database Engine. static int ISOLATION_READ_COMMITTED Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur. static int ISOLATION_READ_UNCOMMITTED Indicates that dirty reads, non-repeatable reads and phantom reads can occur. Field Summary (2) Interface TransactionDefinition
  • 11.
    (2) Interface TransactionDefinition static int ISOLATION_REPEATABLE_READ Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur. static int ISOLATION_SERIALIZABLE Indicates that dirty reads, non-repeatable reads and phantom reads are prevented. static int PROPAGATION_MANDATORY Support a current transaction; throw an exception if no current transaction exists.
  • 12.
    (2) Interface TransactionDefinition static int PROPAGATION_NESTED Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else. static int PROPAGATION_NEVER Do not support a current transaction; throw an exception if a current transaction exists. static int PROPAGATION_NOT_SUPPORTED Do not support a current transaction; rather always execute non-transactionally. static int PROPAGATION_REQUIRED Support a current transaction; create a new one if none exists.
  • 13.
    (2) Interface TransactionDefinition static int PROPAGATION_REQUIRES_NEW Create a new transaction, suspending the current transaction if one exists. static int PROPAGATION_SUPPORTS Support a current transaction; execute non-transactionally if none exists. static int TIMEOUT_DEFAULT Use the default timeout of the underlying transaction system, or none if timeouts are not supported.
  • 14.
    All MethodsInstance MethodsAbstractMethods Modifier and Type Method and Description int getIsolationLevel() Return the isolation level. String getName() Return the name of this transaction. int getPropagationBehavior() Return the propagation behavior. int getTimeout() Return the transaction timeout. boolean isReadOnly() Return whether to optimize as a read-only transaction. Method Summary (2) Interface TransactionDefinition
  • 15.
    Modifier and TypeMethod and Description void flush() Flush the underlying session to the datastore, if applicable: for example, all affected Hibernate/JPA sessions. boolean hasSavepoint() Return whether this transaction internally carries a savepoint, that is, has been created as nested transaction based on a savepoint. boolean isCompleted() Return whether this transaction is completed, that is, whether it has already been committed or rolled back. boolean isNewTransaction() Return whether the present transaction is new (else participating in an existing transaction, or potentially not running in an actual transaction in the first place). boolean isRollbackOnly() Return whether the transaction has been marked as rollback-only (either by the application or by the transaction infrastructure). void setRollbackOnly() Set the transaction rollback-only. Method Summary (3) Interface TransactionStatus
  • 16.
    Conclusion • TheSpring transaction management mechanism is very powerful. • It can integrate any persistence framework • A future post Part – 2 will explain more details of Programmatic and Declarative Transaction.
  • 17.
    Do you haveQuestions ? Please Discuss :

Editor's Notes

  • #7 Refer Link: Global Transactoin : http://www.javacodegeeks.com/2013/07/spring-jta-multiple-resource-transactions-in-tomcat-with-atomikos-example.html
  • #10 Refer Links : http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/PlatformTransactionManager.html 1) The key to the Spring transaction abstraction is defined by theorg.springframework.transaction.PlatformTransactionManager interface. commit(TransactionStatus status) 2) the transaction must be fully completed and cleaned up. No rollback call should be expected in such a case. rollback(TransactionStatus status) 3) Do not call rollback on a transaction if commit threw an exception. :  a rollback call after commit failure will lead to an IllegalTransactionStateException. getTransaction(TransactionDefinition definition) 4) Return a currently active transaction or create a new one, according to the specified propagation behavior. - Parameters: definition - TransactionDefinition instance (can be null for defaults), describing propagation behavior, isolation level, read-only timeout etc.
  • #11 The TransactionDefinition interface specifies: 1) Isolation: The degree to which this transaction is isolated from the work of other transactions. For example, can this transaction see uncommitted writes from other transactions? 2) Propagation: Typically, all code executed within a transaction scope will run in that transaction. However, you have the option of specifying the behavior in the event that a transactional method is executed when a transaction context already exists. For example, code can continue running in the existing transaction (the common case); or the existing transaction can be suspended and a new transaction created. Spring offers all of the transaction propagation options familiar from EJB CMT. To read about the semantics of transaction propagation in Spring, see Section 11.5.7, “Transaction propagation”. 3) Timeout: How long this transaction runs before timing out and being rolled back automatically by the underlying transaction infrastructure. 4) Read-only status: A read-only transaction can be used when your code reads but does not modify data. Read-only transactions can be a useful optimization in some cases, such as when you are using Hibernate. Refer Link : http://stackoverflow.com/questions/8490852/spring-transactional-isolation-propagation http://www.byteslounge.com/tutorials/spring-transaction-isolation-tutorial 2) Propagation : Defines how transactions relate to each other. 1) Isolation : Defines the data contract between transactions. Read Uncommitted: Allows dirty reads Read Committed: Does not allow dirty reads Repeatable Read: If a row is read twice in the same transaction, result will always be the same Serializable: Performs all transactions in a sequence This leads to a scenario where none of the issues mentioned above may occur, but in the other way we don't allow transaction concurrency and consequently introduce a performance penalty. The different levels have different performance characteristics in a multi threaded application. I think if you understand the dirty reads concept you will be able to select a good option. thread 1 thread 2 | | write(x) | | | | read(x) | | rollback | v v value (x) is now dirty (incorrect)   Scenario 1.If T1 transaction reads data from table A1 that was written by another concurrent transaction T2.If on the way T2 is rollback,the data obtained by T1 is invalid one.E.g a=2 is original data .If T1 read a=1 that was written by T2.If T2 rollback then a=1 will be rollback to a=2 in DB.But,Now ,T1 has a=1 but in DB table it is changed to a=2. Scenario2.If T1 transaction reads data from table A1.If another concurrent transaction(T2) update data on table A1.Then the data that T1 has read is different from table A1.Because T2 has updated the data on table A1.E.g if T1 read a=1 and T2 updated a=2.Then a!=b. Scenario 3.If T1 transaction reads data from table A1 with certain number of rows. If another concurrent transaction(T2) inserts more rows on table A1.The number of rows read by T1 is different from rows on table A1 Scenario 1 is called Dirty reads Scenario 2 is called Nonrepeatable reads Scenario 3 is called Phantom reads .
  • #13 7 Propagation Refer Link : http://forum.spring.io/forum/spring-projects/data/7372-propagation-nested-versus-propagation-requires-new http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/TransactionDefinition.html http://www.byteslounge.com/tutorials/spring-transaction-propagation-tutorial https://pubs.vmware.com/vfabric5/index.jsp?topic=/com.vmware.vfabric.gemfire.6.6/developing/transactions/transactional_and_nontransactional_ops.html PROPAGATION_NESTED on the other hand starts a “nested” transaction, which is a true sub transaction of the existing one. What will happen is that a savepoint will be taken at the start of the nested transaction. If the nested transaction fails, we will roll back to that savepoint. The nested transaction is part of of the outer transaction, so it will only be committed at the end of of the outer transaction. 2) PROPAGATION_NEVER Do not support a current transaction; throw an exception if a current transaction exists. The NEVER behavior states that an existing opened transaction must not already exist. If a transaction exists an exception will be thrown by the container. 3) PROPAGATION_NOT_SUPPORTED The NOT_SUPPORTED behavior will execute outside of the scope of any transaction. If an opened transaction already exists it will be paused. 4) PROPAGATION_REQUIRED: Spring REQUIRED behavior means that the same transaction will be used if there is an already opened transaction in the current bean method execution context. Create a new one if none exists. In short this means that if an inner(2nd Transaction) method causes a transaction to rollback, the outer(1st Transaction) method will fail to commit and will also rollback the transaction.
  • #14 1) PROPAGATION_REQUIRES_NEW Create a new transaction, suspending the current transaction if one exists.  The inner method is annotated with REQUIRES_NEW and throws a RuntimeException so it will set its transaction to rollback but will not affect the outer transaction. The outer transaction is paused when the inner transaction starts and then resumes after the inner transaction is concluded. They run independently of each other so the outer transaction may commit successfully. 2) PROPAGATION_SUPPORTS
  • #15 getName() In case of Spring's declarative transactions, the exposed name will be the fully-qualified class name + "." + method name (by default). 2) isReadOnly A read-only transaction can be used when your code reads but does not modify data.