spring transaction management

Click here to load reader

Upload: ye-win

Post on 13-Jul-2015

281 views

Category:

Technology


0 download

TRANSCRIPT

PowerPoint Presentation

Part - 1Spring and Transaction

Ye Win12/08/2014

Who This Slide Is For?IntroductionLocal Vs Global TransactionsProgrammatic Vs DeclarativeSpring Transaction AbstractionsProgrammatic & Declarative (Practical)Conclusion

ContentsPs. Slide notes from Spring Transaction Abstractions Section are soul for this slide.

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=0B72s1dEbEPzBLS00M0JNZDd0X3c&authuser=0

Who This Slide Is For?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:

Atomicity: A transaction should be treated as a single unit of operation which means either the entire sequence of operations is successful or unsuccessful.

Consistency: This represents the consistency of the referential integrity of the database, unique primary keys in tables etc.

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.

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. IntroductionLocal 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. Local Vs Global TansactionsRefer Link: Global Transactoin : http://www.javacodegeeks.com/2013/07/spring-jta-multiple-resource-transactions-in-tomcat-with-atomikos-example.html6Spring supports two types of transaction management:

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.

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. Programmatic Vs DeclarativeWe have to implements mainly three transaction interface.

org.springframework.transaction.PlatformTransactionManager

org.springframework.transaction.TransactionDefinition

org.springframework.transaction.TransactionStatus

Spring Transaction AbstractionsMethod SummaryModifier and TypeMethod and Descriptionvoidcommit(TransactionStatusstatus)Commit the given transaction, with regard to its status.TransactionStatusgetTransaction(TransactionDefinitiondefinition)Return a currently active transaction or create a new one, according to the specified propagation behavior.voidrollback(TransactionStatusstatus)Perform a rollback of the given transaction.(1) Interface PlatformTransactionManagerRefer 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(TransactionStatusstatus)2) the transaction must be fully completed and cleaned up. No rollback call should be expected in such a case. rollback(TransactionStatusstatus)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(TransactionDefinitiondefinition)4) Return a currently active transaction or create a new one, according to the specified propagation behavior. - Parameters: definition- TransactionDefinition instance (can benullfor defaults), describing propagation behavior, isolation level, read-only timeout etc.9FieldsModifier and TypeField and Descriptionstatic intISOLATION_DEFAULTUse the default isolation level of the underlying datastore.

Eg. READ COMMITTED is the default isolation level for the Microsoft SQL Server Database Engine.static intISOLATION_READ_COMMITTEDIndicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur.static intISOLATION_READ_UNCOMMITTEDIndicates that dirty reads, non-repeatable reads and phantom reads can occur.Field Summary(2) Interface TransactionDefinitionTheTransactionDefinitioninterface 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, seeSection11.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-propagationhttp://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 readsRead Committed: Does not allow dirty readsRepeatable Read: If a row is read twice in the same transaction, result will always be the sameSerializable: Performs all transactions in a sequenceThis leads to a scenario wherenoneof 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 thedirty readsconcept 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 calledDirty readsScenario 2 is calledNonrepeatable readsScenario 3 is calledPhantom reads .

10static intISOLATION_REPEATABLE_READIndicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur.static intISOLATION_SERIALIZABLEIndicates that dirty reads, non-repeatable reads and phantom reads are prevented.static intPROPAGATION_MANDATORYSupport a current transaction; throw an exception if no current transaction exists.(2) Interface TransactionDefinition11static intPROPAGATION_NESTEDExecute within a nested transaction if a current transaction exists, behave likePROPAGATION_REQUIREDelse.static intPROPAGATION_NEVERDo not support a current transaction; throw an exception if a current transaction exists.static intPROPAGATION_NOT_SUPPORTEDDo not support a current transaction; rather always execute non-transactionally.static intPROPAGATION_REQUIREDSupport a current transaction; create a new one if none exists.(2) Interface TransactionDefinition7 PropagationRefer Link : http://forum.spring.io/forum/spring-projects/data/7372-propagation-nested-versus-propagation-requires-newhttp://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/TransactionDefinition.htmlhttp://www.byteslounge.com/tutorials/spring-transaction-propagation-tutorialhttps://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 subtransaction 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_NEVERDo not support a current transaction; throw an exception if a current transaction exists.TheNEVERbehavior states that an existing opened transaction mustnotalready exist. If a transaction exists an exception will be thrown by the container.

3) PROPAGATION_NOT_SUPPORTEDTheNOT_SUPPORTEDbehavior will execute outside of the scope of any transaction. If an opened transaction already exists it will be paused.

4) PROPAGATION_REQUIREDSpringREQUIREDbehavior 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.12static intPROPAGATION_REQUIRES_NEWCreate a new transaction, suspending the current transaction if one exists.static intPROPAGATION_SUPPORTSSupport a current transaction; execute non-transactionally if none exists.static intTIMEOUT_DEFAULTUse the default timeout of the underlying transaction system, or none if timeouts are not supported.(2) Interface TransactionDefinition1) PROPAGATION_REQUIRES_NEWCreate a new transaction, suspending the current transaction if one exists.The inner method is annotated withREQUIRES_NEWand throws aRuntimeExceptionso it will set its transaction to rollback but willnotaffect 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

13All MethodsInstance MethodsAbstract MethodsModifier and TypeMethod and DescriptionintgetIsolationLevel()Return the isolation level.StringgetName()Return the name of this transaction.intgetPropagationBehavior()Return the propagation behavior.intgetTimeout()Return the transaction timeout.booleanisReadOnly()Return whether to optimize as a read-only transaction.Method Summary(2) Interface TransactionDefinitiongetName()In case of Spring's declarative transactions, the exposed name will be thefully-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. 14Modifier and TypeMethod and Descriptionvoidflush()Flush the underlying session to the datastore, if applicable: for example, all affected Hibernate/JPA sessions.booleanhasSavepoint()Return whether this transaction internally carries a savepoint, that is, has been created as nested transaction based on a savepoint.booleanisCompleted()Return whether this transaction is completed, that is, whether it has already been committed or rolled back.booleanisNewTransaction()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).booleanisRollbackOnly()Return whether the transaction has been marked as rollback-only (either by the application or by the transaction infrastructure).voidsetRollbackOnly()Set the transaction rollback-only.Method Summary(3) Interface TransactionStatus15ConclusionThe 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.

Please Discuss :

Do you have Questions ?