SPRING TRANSACTION MANAGEMENT
HARSHIT CHOUDHARY
OUTLINE
 Introduction to Transaction
 Introduction to Spring Framework Transaction Management
 Global Transaction vs Local Transaction
 Declarative Transaction Management
 Programmatic Transaction Management
 Choosing Between programmatic and declarative transaction Management
HARSHIT CHOUDHARY
WHAT IS TRANSACTION
 A transaction is a unit of work in which either all operations must execute or none of
them
 Lets take a scenario – Transfer funds from one account to another, this operation
includes below two steps
 Deduct the amount from sender’s account
 Add the amount to receiver’s account
 Think of a situation where amount gets deducted from sender’s account but could
not get added to receiver’s account because of some error
 In such cases, transaction management is done in which both the steps are
performed as a single unit of work where either both steps are performed
successfully or both gets rolled back in case of error
HARSHIT CHOUDHARY
SPRING TRANSACTION MANAGEMENT
 The Spring Framework provides a consistent abstraction for transaction management that
delivers the following benefits:
 Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC,
Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO).
 Support for declarative transaction management.
 Simpler API for programmatic transaction management than complex transaction APIs such as JTA.
 Excellent integration with Spring’s data access abstractions.
HARSHIT CHOUDHARY
LOCAL AND GLOBAL TRANSACTIONS
HARSHIT CHOUDHARY
Global TransactionsLocal Transactions
Supports multiple transactional
resources Ex. Relational databases and
message queues
 Managed by Application server using
JTA
 Need to use JNDI in order to use JTA
 Involves multiple resource managers
and also a transaction manager that
coordinates the resources.
 Resource-specific Ex.
transaction associated with a JDBC
connection
 Involves a single Transactional
resource manager
 Cannot work across multiple
transactional resources
 Application server is not
involved
SPRING FRAMEWORK’S CONSISTENT PROGRAMMING MODEL
 Spring resolves the disadvantages of global and local transactions.
 It enables application developers to use a consistent programming model in
any environment.
 You write your code once, and it can benefit from different transaction
management strategies in different environments
HARSHIT CHOUDHARY
SPRING TRANSACTION MANAGEMENT SUPPORT
 Spring supports both
 Declarative Transaction Management
 Separates transaction code from business methods via declarations
 Provides a great configurability using configuration files
 Less code, non-invasive and hence most preferred
 Do not depend on the Spring Framework transaction API, or any other transaction API.
 Programmatic Transaction Management
 Transaction management code is included in business methods to control the commit and rollback of transactions
 Developers work with the Spring Framework transaction abstraction, which can run over any underlying transaction
infrastructure
 Gives fine control on transaction boundaries,
HARSHIT CHOUDHARY
SPRING FRAMEWORK TRANSACTION ABSTRACTION
 Spring provides transaction abstraction with the help of org.springframework.transaction.PlatformTransactionManager interface
 This interface defines the below methods
 TransactionStatus getTransaction(TransactionDefinition)
 Returns a TransactionStatus object, depending on TransactionDefinition parameter.
 The returned TransactionStatus might represents a new Transaction or an existing active transaction
 void commit(TransactionStatus)
 Commits the transaction object being passed
 void rollback(TransactionStatus)
 Rollbacks the transaction object being passed
 Regardless of Programmatic or Declarative Transaction Management, PlatformTransactionManager implementation has to be defined correctly
 Few of the Implementations are discussed in next slide.
HARSHIT CHOUDHARY
CHOOSING TRANSACTION MANAGER
 Spring supports several transaction managers which delegate the transaction management responsibilities to platform
specific implementations
 Some of the transaction Managers are:
 DataSource Transaction Manager
 For simple JDBC persistence mechanism
 Hibernate Transaction Manager
 Used when application is using Hibernate for Database connectivity
 JDO Transaction Manager
 Java data object transaction manager
 JTA Transaction Manager
 If our transaction is across multiple data sources than we need to use Java Transactions API transactions . Internally JTA implementation
handles transaction responsibility.
HARSHIT CHOUDHARY
TRANSACTIONDEFINITION
 The Transaction Definition interface controls the properties of a transaction
 Transaction 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?
 Transaction Propagation
 Normally all code executed within a transaction scope will run in that transaction. However, there are several options
specifying behavior if a transactional method is executed when a transaction context already exists
 Transaction timeout
 How long this transaction may run before timing out (automatically being rolled back by the underlying transaction
infrastructure)
 Read-only status
 Read-only transaction can be used when your code reads but does not modify data
HARSHIT CHOUDHARY
ISOLATION LEVELS
 Defines the data contract between transactions
 The Different Isolation Levels are:
 Read Uncommitted
 User A will see the changes made by User B. Called dirty reads, which means that the read data is not consistent with other parts of the
table or the query and may not yet have been committed
 Read Committed
 Cannot read uncommitted data.
 Repeatable Read
 Cannot change data that is being read by a different transaction.
 Serializable
 Different transactions can neither read nor write to the same data
 All transactions occur in a completely isolated fashion
 Most restrictive
HARSHIT CHOUDHARY
ISOLATION LEVELS DEFINED BY TRANSACTIONDEFINITION
 TransactionDefinition.ISOLATION_DEFAULT
 TransactionDefinition.READ_COMMITTED
 TransactionDefinition.READ_UNCOMMITTED
 TransactionDefinition.REPEATABLE_READ
 TransactionDefinition.SERIALIZABLE
HARSHIT CHOUDHARY
PROPAGATION LEVELS
 Controls the scope of a transaction
 If a method -methodA in one Service class invokes method-methodB of another Service class. When methodB
executes, does it run within the scope of the transaction started by methodA or does it execute within a new
transaction?
 The answer depends on the transaction of methodB.
 The propagation levels are
 Required
 RequiresNew
 Mandatory
 Never
 NotSupported
 Supports
 Nested
HARSHIT CHOUDHARY
PROPAGATION LEVELS
 Required
 If a client is running within a transaction and invokes a service method, the method executes within client’s transaction.
 Otherwise spring starts a new transaction before running the method
 RequiresNew
 If a client is running within a transaction and invokes a service method, spring takes the following steps
 Suspends the client transaction
 Starts a new transaction
 Delegates the call to method
 Resumes the client’s transaction after the method completes
 Otherwise spring starts a new transaction before running the method
 Mandatory
 If a client is running within a transaction and invokes a service method, the method executes within client’s transaction.
 Otherwise IllegalTransactionStateException is thrown.
HARSHIT CHOUDHARY
PROPAGATION LEVELS
 Never
 If a client is running within a transaction and invokes a service method, IllegalTransactionStateException is thrown
 Otherwise the method is executed
 Not Supported
 If a client is running within a transaction and invokes a service method, spring container suspends the client’s transaction before running the
method.
 After method completion, the transaction is resumed.
 If there is no transaction running, no new transaction is started
 Supports
 If a client is running within a transaction and invokes a service method, the method executes within client’s transaction
 If there is no transaction running, no new transaction is started
 Nested
 The NESTED behavior makes nested Spring transactions to use the same physical transaction but sets savepoints between nested
invocations so inner transactions may also rollback independently of outer transactions
HARSHIT CHOUDHARY
PROPAGATION LEVELS DEFINED BY TRANSACTIONDEFINITION
 TransactionDefinition.PROPAGATION_MANDATORY
 TransactionDefinition.PROPAGATION_NEVER
 TransactionDefinition.PROPAGATION_REQUIRED
 TransactionDefinition.PROPAGATION_REQUIRES_NEW
 TransactionDefinition.PROPAGATION_SUPPORTS
 TransactionDefinition.PROPAGATION_NOT_SUPPORTED
 TransactionDefinition.PROPAGATION_NESTED
HARSHIT CHOUDHARY
TRANSACTIONSTATUS INTERFACE
 Provides a simple way for transactional code to control transaction execution
and query transaction status
 Some of the methods of TransactionStatus interface are:
 boolean isNewTransaction()
 void setRollbackOnly()
 boolean isRollbackOnly()
 boolean isCompleted()
HARSHIT CHOUDHARY
DECLARATIVE TRANSACTION MANAGEMENT
HARSHIT CHOUDHARY
DECLARATIVE TRANSACTION MANAGEMENT
 Made possible with Spring AOP.
 Works with JTA Transactions or local transactions using JDBC, JPA or Hibernate by simple adjusting the
configuration files
 Can be applied to any class
 offers declarative rollback rules - they enable you to specify which exceptions (and throwables) should cause
automatic rollback declaratively in configuration files
 Does not support propagation of transaction contexts across remote calls, as do high-end application servers.
HARSHIT CHOUDHARY
SPRING’S DECLARATIVE TRANSACTION IMPLEMENTATION
• Transaction support is enabled by AOP Proxy
• Transactional advice is driven by metadata
(XML or annotation)
• The AOP proxy uses a TransactionInterceptor
in conjuction with an appropriate
PlatformTransactionManager implementation
to drive transactions.
HARSHIT CHOUDHARY
ANNOTATION FOR DECLARATIVE TRANSACTION MANAGEMENT
 @Transactional
 Used either at class level or method level
 Using at class level makes all the methods in that class take part in Transaction
Management
 Using at method level makes only a particular method part of Transaction Management
HARSHIT CHOUDHARY
ENABLING CONFIGURATION IN SPRING
 XML File
 Java Config
 Adding @EnableTransactionManagement annotation to the @Configuration class.
HARSHIT CHOUDHARY
@TRANSACTIONAL SETTINGS
 The default transactional settings are as below:
 Propagation Setting is PROPAGATION_REQUIRED
 Isolation level is ISOLATION_DEFAULT
 Transaction is read/write
 Transaction timeout defaults to the default timeout of the underlying transaction system,
or to none if timeouts are not supported
 Any RuntimeException triggers rollback, and any checked exception does not
HARSHIT CHOUDHARY
@TRANSACTIONAL SETTINGS
HARSHIT CHOUDHARY
Property Type Description
Value String Optional qualifier specifying the transaction manager to be
used
Propagation Enum (Propagation) Optional propagation setting.
Isolation Enum (Isolation) Optional isolation level
readOnly Boolean Read/write vs. read-only transaction
Timeout Int (in seconds) Transaction timeout.
rollbackFor Array of Class objects Optional array of exception classes that must cause rollback.
rollbackForClassName Array of Class names Optional array of names of exception classes that must cause
rollback.
noRollbackFor Array of Class objects Optional array of exception classes that must not cause
rollback.
noRollbackForClassName Array of Class names Optional array of names of exception classes that must
notcause rollback.
CHOOSING BETWEEN PROGRAMMATIC AND DECLARATIVE
TRANSACTION MANAGEMENT
 Programmatic Transaction Management in case we have a small number of transactional operations
 Declarative Transaction Management in case the application has numerous transactional operations. It
keeps transaction management out of business logic and is not difficult to configure.
HARSHIT CHOUDHARY

Spring transaction management

  • 1.
  • 2.
    OUTLINE  Introduction toTransaction  Introduction to Spring Framework Transaction Management  Global Transaction vs Local Transaction  Declarative Transaction Management  Programmatic Transaction Management  Choosing Between programmatic and declarative transaction Management HARSHIT CHOUDHARY
  • 3.
    WHAT IS TRANSACTION A transaction is a unit of work in which either all operations must execute or none of them  Lets take a scenario – Transfer funds from one account to another, this operation includes below two steps  Deduct the amount from sender’s account  Add the amount to receiver’s account  Think of a situation where amount gets deducted from sender’s account but could not get added to receiver’s account because of some error  In such cases, transaction management is done in which both the steps are performed as a single unit of work where either both steps are performed successfully or both gets rolled back in case of error HARSHIT CHOUDHARY
  • 4.
    SPRING TRANSACTION MANAGEMENT The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:  Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO).  Support for declarative transaction management.  Simpler API for programmatic transaction management than complex transaction APIs such as JTA.  Excellent integration with Spring’s data access abstractions. HARSHIT CHOUDHARY
  • 5.
    LOCAL AND GLOBALTRANSACTIONS HARSHIT CHOUDHARY Global TransactionsLocal Transactions Supports multiple transactional resources Ex. Relational databases and message queues  Managed by Application server using JTA  Need to use JNDI in order to use JTA  Involves multiple resource managers and also a transaction manager that coordinates the resources.  Resource-specific Ex. transaction associated with a JDBC connection  Involves a single Transactional resource manager  Cannot work across multiple transactional resources  Application server is not involved
  • 6.
    SPRING FRAMEWORK’S CONSISTENTPROGRAMMING MODEL  Spring resolves the disadvantages of global and local transactions.  It enables application developers to use a consistent programming model in any environment.  You write your code once, and it can benefit from different transaction management strategies in different environments HARSHIT CHOUDHARY
  • 7.
    SPRING TRANSACTION MANAGEMENTSUPPORT  Spring supports both  Declarative Transaction Management  Separates transaction code from business methods via declarations  Provides a great configurability using configuration files  Less code, non-invasive and hence most preferred  Do not depend on the Spring Framework transaction API, or any other transaction API.  Programmatic Transaction Management  Transaction management code is included in business methods to control the commit and rollback of transactions  Developers work with the Spring Framework transaction abstraction, which can run over any underlying transaction infrastructure  Gives fine control on transaction boundaries, HARSHIT CHOUDHARY
  • 8.
    SPRING FRAMEWORK TRANSACTIONABSTRACTION  Spring provides transaction abstraction with the help of org.springframework.transaction.PlatformTransactionManager interface  This interface defines the below methods  TransactionStatus getTransaction(TransactionDefinition)  Returns a TransactionStatus object, depending on TransactionDefinition parameter.  The returned TransactionStatus might represents a new Transaction or an existing active transaction  void commit(TransactionStatus)  Commits the transaction object being passed  void rollback(TransactionStatus)  Rollbacks the transaction object being passed  Regardless of Programmatic or Declarative Transaction Management, PlatformTransactionManager implementation has to be defined correctly  Few of the Implementations are discussed in next slide. HARSHIT CHOUDHARY
  • 9.
    CHOOSING TRANSACTION MANAGER Spring supports several transaction managers which delegate the transaction management responsibilities to platform specific implementations  Some of the transaction Managers are:  DataSource Transaction Manager  For simple JDBC persistence mechanism  Hibernate Transaction Manager  Used when application is using Hibernate for Database connectivity  JDO Transaction Manager  Java data object transaction manager  JTA Transaction Manager  If our transaction is across multiple data sources than we need to use Java Transactions API transactions . Internally JTA implementation handles transaction responsibility. HARSHIT CHOUDHARY
  • 10.
    TRANSACTIONDEFINITION  The TransactionDefinition interface controls the properties of a transaction  Transaction 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?  Transaction Propagation  Normally all code executed within a transaction scope will run in that transaction. However, there are several options specifying behavior if a transactional method is executed when a transaction context already exists  Transaction timeout  How long this transaction may run before timing out (automatically being rolled back by the underlying transaction infrastructure)  Read-only status  Read-only transaction can be used when your code reads but does not modify data HARSHIT CHOUDHARY
  • 11.
    ISOLATION LEVELS  Definesthe data contract between transactions  The Different Isolation Levels are:  Read Uncommitted  User A will see the changes made by User B. Called dirty reads, which means that the read data is not consistent with other parts of the table or the query and may not yet have been committed  Read Committed  Cannot read uncommitted data.  Repeatable Read  Cannot change data that is being read by a different transaction.  Serializable  Different transactions can neither read nor write to the same data  All transactions occur in a completely isolated fashion  Most restrictive HARSHIT CHOUDHARY
  • 12.
    ISOLATION LEVELS DEFINEDBY TRANSACTIONDEFINITION  TransactionDefinition.ISOLATION_DEFAULT  TransactionDefinition.READ_COMMITTED  TransactionDefinition.READ_UNCOMMITTED  TransactionDefinition.REPEATABLE_READ  TransactionDefinition.SERIALIZABLE HARSHIT CHOUDHARY
  • 13.
    PROPAGATION LEVELS  Controlsthe scope of a transaction  If a method -methodA in one Service class invokes method-methodB of another Service class. When methodB executes, does it run within the scope of the transaction started by methodA or does it execute within a new transaction?  The answer depends on the transaction of methodB.  The propagation levels are  Required  RequiresNew  Mandatory  Never  NotSupported  Supports  Nested HARSHIT CHOUDHARY
  • 14.
    PROPAGATION LEVELS  Required If a client is running within a transaction and invokes a service method, the method executes within client’s transaction.  Otherwise spring starts a new transaction before running the method  RequiresNew  If a client is running within a transaction and invokes a service method, spring takes the following steps  Suspends the client transaction  Starts a new transaction  Delegates the call to method  Resumes the client’s transaction after the method completes  Otherwise spring starts a new transaction before running the method  Mandatory  If a client is running within a transaction and invokes a service method, the method executes within client’s transaction.  Otherwise IllegalTransactionStateException is thrown. HARSHIT CHOUDHARY
  • 15.
    PROPAGATION LEVELS  Never If a client is running within a transaction and invokes a service method, IllegalTransactionStateException is thrown  Otherwise the method is executed  Not Supported  If a client is running within a transaction and invokes a service method, spring container suspends the client’s transaction before running the method.  After method completion, the transaction is resumed.  If there is no transaction running, no new transaction is started  Supports  If a client is running within a transaction and invokes a service method, the method executes within client’s transaction  If there is no transaction running, no new transaction is started  Nested  The NESTED behavior makes nested Spring transactions to use the same physical transaction but sets savepoints between nested invocations so inner transactions may also rollback independently of outer transactions HARSHIT CHOUDHARY
  • 16.
    PROPAGATION LEVELS DEFINEDBY TRANSACTIONDEFINITION  TransactionDefinition.PROPAGATION_MANDATORY  TransactionDefinition.PROPAGATION_NEVER  TransactionDefinition.PROPAGATION_REQUIRED  TransactionDefinition.PROPAGATION_REQUIRES_NEW  TransactionDefinition.PROPAGATION_SUPPORTS  TransactionDefinition.PROPAGATION_NOT_SUPPORTED  TransactionDefinition.PROPAGATION_NESTED HARSHIT CHOUDHARY
  • 17.
    TRANSACTIONSTATUS INTERFACE  Providesa simple way for transactional code to control transaction execution and query transaction status  Some of the methods of TransactionStatus interface are:  boolean isNewTransaction()  void setRollbackOnly()  boolean isRollbackOnly()  boolean isCompleted() HARSHIT CHOUDHARY
  • 18.
  • 19.
    DECLARATIVE TRANSACTION MANAGEMENT Made possible with Spring AOP.  Works with JTA Transactions or local transactions using JDBC, JPA or Hibernate by simple adjusting the configuration files  Can be applied to any class  offers declarative rollback rules - they enable you to specify which exceptions (and throwables) should cause automatic rollback declaratively in configuration files  Does not support propagation of transaction contexts across remote calls, as do high-end application servers. HARSHIT CHOUDHARY
  • 20.
    SPRING’S DECLARATIVE TRANSACTIONIMPLEMENTATION • Transaction support is enabled by AOP Proxy • Transactional advice is driven by metadata (XML or annotation) • The AOP proxy uses a TransactionInterceptor in conjuction with an appropriate PlatformTransactionManager implementation to drive transactions. HARSHIT CHOUDHARY
  • 21.
    ANNOTATION FOR DECLARATIVETRANSACTION MANAGEMENT  @Transactional  Used either at class level or method level  Using at class level makes all the methods in that class take part in Transaction Management  Using at method level makes only a particular method part of Transaction Management HARSHIT CHOUDHARY
  • 22.
    ENABLING CONFIGURATION INSPRING  XML File  Java Config  Adding @EnableTransactionManagement annotation to the @Configuration class. HARSHIT CHOUDHARY
  • 23.
    @TRANSACTIONAL SETTINGS  Thedefault transactional settings are as below:  Propagation Setting is PROPAGATION_REQUIRED  Isolation level is ISOLATION_DEFAULT  Transaction is read/write  Transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported  Any RuntimeException triggers rollback, and any checked exception does not HARSHIT CHOUDHARY
  • 24.
    @TRANSACTIONAL SETTINGS HARSHIT CHOUDHARY PropertyType Description Value String Optional qualifier specifying the transaction manager to be used Propagation Enum (Propagation) Optional propagation setting. Isolation Enum (Isolation) Optional isolation level readOnly Boolean Read/write vs. read-only transaction Timeout Int (in seconds) Transaction timeout. rollbackFor Array of Class objects Optional array of exception classes that must cause rollback. rollbackForClassName Array of Class names Optional array of names of exception classes that must cause rollback. noRollbackFor Array of Class objects Optional array of exception classes that must not cause rollback. noRollbackForClassName Array of Class names Optional array of names of exception classes that must notcause rollback.
  • 25.
    CHOOSING BETWEEN PROGRAMMATICAND DECLARATIVE TRANSACTION MANAGEMENT  Programmatic Transaction Management in case we have a small number of transactional operations  Declarative Transaction Management in case the application has numerous transactional operations. It keeps transaction management out of business logic and is not difficult to configure. HARSHIT CHOUDHARY