SlideShare a Scribd company logo
1 of 25
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

More Related Content

What's hot

What's hot (20)

Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
 
Building Event-Driven Services with Apache Kafka
Building Event-Driven Services with Apache KafkaBuilding Event-Driven Services with Apache Kafka
Building Event-Driven Services with Apache Kafka
 
spring-boot-fr.pdf
spring-boot-fr.pdfspring-boot-fr.pdf
spring-boot-fr.pdf
 
Javascript under the hood 1
Javascript under the hood 1Javascript under the hood 1
Javascript under the hood 1
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
servlet in java
servlet in javaservlet in java
servlet in java
 
Kafka: All an engineer needs to know
Kafka: All an engineer needs to knowKafka: All an engineer needs to know
Kafka: All an engineer needs to know
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
 
Systemes authentification
Systemes authentificationSystemes authentification
Systemes authentification
 
Tiered Compilation in Hotspot JVM
Tiered Compilation in Hotspot JVMTiered Compilation in Hotspot JVM
Tiered Compilation in Hotspot JVM
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Distributed Transactions: Saga Patterns
Distributed Transactions: Saga PatternsDistributed Transactions: Saga Patterns
Distributed Transactions: Saga Patterns
 
Building Event Driven Architectures with Kafka and Cloud Events (Dan Rosanova...
Building Event Driven Architectures with Kafka and Cloud Events (Dan Rosanova...Building Event Driven Architectures with Kafka and Cloud Events (Dan Rosanova...
Building Event Driven Architectures with Kafka and Cloud Events (Dan Rosanova...
 
Embedding Jaspersoft into your PHP application
Embedding Jaspersoft into your PHP applicationEmbedding Jaspersoft into your PHP application
Embedding Jaspersoft into your PHP application
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 

Similar to Spring transaction management

Atomic Service Transactions
Atomic Service Transactions Atomic Service Transactions
Atomic Service Transactions
WSO2
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
patinijava
 
Session 9 Tp9
Session 9 Tp9Session 9 Tp9
Session 9 Tp9
phanleson
 
Why Coordination And Transactions Are Key To Building An Operational Soa
Why Coordination And Transactions Are Key To Building An Operational SoaWhy Coordination And Transactions Are Key To Building An Operational Soa
Why Coordination And Transactions Are Key To Building An Operational Soa
David Linthicum
 
deadlock prevention
deadlock preventiondeadlock prevention
deadlock prevention
Nilu Desai
 
RDB - Repairable Database Systems
RDB - Repairable Database SystemsRDB - Repairable Database Systems
RDB - Repairable Database Systems
Alexey Smirnov
 

Similar to Spring transaction management (20)

Transaction and concurrency pitfalls in Java
Transaction and concurrency pitfalls in JavaTransaction and concurrency pitfalls in Java
Transaction and concurrency pitfalls in Java
 
Spring transaction part4
Spring transaction   part4Spring transaction   part4
Spring transaction part4
 
Distributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEEDistributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEE
 
Atomic Service Transactions
Atomic Service Transactions Atomic Service Transactions
Atomic Service Transactions
 
Managing transactions 11g release 1 (10.3
Managing transactions   11g release 1 (10.3Managing transactions   11g release 1 (10.3
Managing transactions 11g release 1 (10.3
 
Java Distributed Transactions
Java Distributed TransactionsJava Distributed Transactions
Java Distributed Transactions
 
MuleSoft Meetup: Transaction Management
MuleSoft Meetup: Transaction ManagementMuleSoft Meetup: Transaction Management
MuleSoft Meetup: Transaction Management
 
Trafodion Distributed Transaction Management
Trafodion Distributed Transaction ManagementTrafodion Distributed Transaction Management
Trafodion Distributed Transaction Management
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
 
Wcf Transaction Handling
Wcf Transaction HandlingWcf Transaction Handling
Wcf Transaction Handling
 
Session 9 Tp9
Session 9 Tp9Session 9 Tp9
Session 9 Tp9
 
Why Coordination And Transactions Are Key To Building An Operational Soa
Why Coordination And Transactions Are Key To Building An Operational SoaWhy Coordination And Transactions Are Key To Building An Operational Soa
Why Coordination And Transactions Are Key To Building An Operational Soa
 
deadlock prevention
deadlock preventiondeadlock prevention
deadlock prevention
 
Acid Properties In Database Management System
Acid Properties In Database Management SystemAcid Properties In Database Management System
Acid Properties In Database Management System
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction Management
 
Job Opportunity
Job OpportunityJob Opportunity
Job Opportunity
 
Rdbms1
Rdbms1Rdbms1
Rdbms1
 
RDB - Repairable Database Systems
RDB - Repairable Database SystemsRDB - Repairable Database Systems
RDB - Repairable Database Systems
 

Recently uploaded

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Spring transaction management

  • 2. 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
  • 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 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 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 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
  • 11. 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
  • 12. ISOLATION LEVELS DEFINED BY TRANSACTIONDEFINITION  TransactionDefinition.ISOLATION_DEFAULT  TransactionDefinition.READ_COMMITTED  TransactionDefinition.READ_UNCOMMITTED  TransactionDefinition.REPEATABLE_READ  TransactionDefinition.SERIALIZABLE HARSHIT CHOUDHARY
  • 13. 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
  • 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 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
  • 17. 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
  • 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 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
  • 21. 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
  • 22. ENABLING CONFIGURATION IN SPRING  XML File  Java Config  Adding @EnableTransactionManagement annotation to the @Configuration class. HARSHIT CHOUDHARY
  • 23. @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
  • 24. @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.
  • 25. 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