Transaction Management in Spring

Last updated on Jan 16 2023
Prabhas Ramanathan

A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the 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 transaction 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.
A real RDBMS database system will guarantee all four properties for each transaction. The simplistic view of a transaction issued to the database using SQL is as follows −
• Begin the transaction using begin transaction command.
• Perform various deleted, update or insert operations using SQL queries.
• If all the operation are successful then perform commit otherwise rollback all the operations.
Spring framework provides an abstract layer on top of different underlying transaction management APIs. Spring’s transaction support aims to provide an alternative to EJB transactions by adding transaction capabilities to POJOs. Spring supports both programmatic and declarative transaction management. EJBs require an application server, but Spring transaction management can be implemented without the need of an application server.

Table of Contents

Local vs. Global Transactions

Local transactions are specific to a single transactional resource like a JDBC connection, whereas global transactions can span multiple transactional resources like transaction in a distributed system.
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 −
• Programmatic transaction management − This means that you have to 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.

Spring Transaction Abstractions

The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as follows −

public interface PlatformTransactionManager {
TransactionStatus getTransaction(TransactionDefinition definition);
throws TransactionException;

void commit(TransactionStatus status) throws TransactionException;
void rollback(TransactionStatus status) throws TransactionException;
}
Sr.No Method & Description
1 TransactionStatus getTransaction(TransactionDefinition definition)

This method returns a currently active transaction or creates a new one, according to the specified propagation behavior.

2 void commit(TransactionStatus status)

This method commits the given transaction, with regard to its status.

3 void rollback(TransactionStatus status)

This method performs a rollback of the given transaction.

The TransactionDefinition is the core interface of the transaction support in Spring and it is defined as follows −

public interface TransactionDefinition {
int getPropagationBehavior();
int getIsolationLevel();
String getName();
int getTimeout();
boolean isReadOnly();
}
Sr.No Method & Description
1 int getPropagationBehavior()

This method returns the propagation behavior. Spring offers all of the transaction propagation options familiar from EJB CMT.

2 int getIsolationLevel()

This method returns the degree to which this transaction is isolated from the work of other transactions.

3 String getName()

This method returns the name of this transaction.

4 int getTimeout()

This method returns the time in seconds in which the transaction must complete.

5 boolean isReadOnly()

This method returns whether the transaction is read-only.

Following are the possible values for isolation level −

Sr.No Isolation & Description
1 TransactionDefinition.ISOLATION_DEFAULT

This is the default isolation level.

2 TransactionDefinition.ISOLATION_READ_COMMITTED

Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

3 TransactionDefinition.ISOLATION_READ_UNCOMMITTED

Indicates that dirty reads, non-repeatable reads, and phantom reads can occur.

4 TransactionDefinition.ISOLATION_REPEATABLE_READ

Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur.

5 TransactionDefinition.ISOLATION_SERIALIZABLE

Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented.

Following are the possible values for propagation types −

Sr.No. Propagation & Description
1 TransactionDefinition.PROPAGATION_MANDATORY

Supports a current transaction; throws an exception if no current transaction exists.

2 TransactionDefinition.PROPAGATION_NESTED

Executes within a nested transaction if a current transaction exists.

3 TransactionDefinition.PROPAGATION_NEVER

Does not support a current transaction; throws an exception if a current transaction exists.

4 TransactionDefinition.PROPAGATION_NOT_SUPPORTED

Does not support a current transaction; rather always execute nontransactionally.

5 TransactionDefinition.PROPAGATION_REQUIRED

Supports a current transaction; creates a new one if none exists.

6 TransactionDefinition.PROPAGATION_REQUIRES_NEW

Creates a new transaction, suspending the current transaction if one exists.

7 TransactionDefinition.PROPAGATION_SUPPORTS

Supports a current transaction; executes non-transactionally if none exists.

8 TransactionDefinition.TIMEOUT_DEFAULT

Uses the default timeout of the underlying transaction system, or none if timeouts are not supported.

The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status.

public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
boolean isCpleted();
}
Sr.No. Method & Description
1 boolean hasSavepoint()

This method returns whether this transaction internally carries a savepoint, i.e., has been created as nested transaction based on a savepoint.

2 boolean isCompleted()

This method returns whether this transaction is completed, i.e., whether it has already been committed or rolled back.

3 boolean isNewTransaction()

This method returns true in case the present transaction is new.

4 boolean isRollbackOnly()

This method returns whether the transaction has been marked as rollback-only.

5 void setRollbackOnly()

This method sets the transaction as rollback-only.

So, this brings us to the end of blog. This Tecklearn ‘Transaction Management in Spring’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Spring and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Transaction Management in Spring"

Leave a Message

Your email address will not be published. Required fields are marked *