You are on page 1of 22

Spring Transactions:

—---------------------
Transaction is a unit of work performed by the Front End application on the
Back End System.

EX: Deposit some amount in an Account.


Withdraw Some amount from an Account
Transfer some amount from one account to another account.
In database Applications, Every transaction must follow the following
properties.

A : Atomicity
C : Consistency
I : Isolation
D : Durability

Atomicity:
In general, in a single transaction we are able to perform a number of
operations, here Atomicity property says that “Either to perform all the
Operations or to perform None of the operations”.

In a transaction, if we perform all the operations then the state of the


Transaction is “SUCCESS”. If we perform NONE of the operations in a
transaction then the state of the Transaction is “FAILURE”.

In Transactions, Atomicity property says that “The Transaction must be in


either SUCCESS State or in FAILURE state”.

EX: In a bank application, in a Transaction like Transfer Funds from one


account to another account, we have to perform debit at sender's account and
credit at receiver's account, in this case if we perform both debit and
credit successfully then the Transaction state is “SUCCESS”, if we perform
none of the operations then the transaction state id “FAILURE”.

2. Consistency:
—--------------
Before Transaction And After transaction the Database must be in stable.
To check Transactions consistency no predefined libraries exist, just we have
to go with manual checkups.
Isolation:
If more than one transaction is executing on a single data then that
transactions are called “Concurrent transactions”.

In the transactions concurrency when more than one transaction is performing


operations on the same data item then there is a chance to get data
inconsistency.

In the above context, to avoid data inconsistency we have to use “isolation”.

In Transactions, Isolations says that “One Transaction Execution should not


give effect to the another transaction Execution”.

To implement transaction Isolation , database related technologies are


providing Isolation levels feature.

Durability:
After committing the transactions if we have any catastrophic failures like
power failure, OS crashing,.... After getting the system ready if we open the
database all the updations which we have performed during the transaction
must be preserved.

To test durability, technologies are not having any predefined library ,


durability must be checked with the manual approaches.
In JDBC applications, to implement atomicity property, the Connection
interface has provided the following conventions.

1. Remove Auto-commit mode from Connection.


con.setAutoCommit(false);

2. At the end of the Transaction, perform either commit operation or


rollback operation by using the following methods.

public void commit()throws SQLException


public void rollback()throws SQLException

Connection con = null;


try{
con = DriverManager.getConnection(“--”,”--”,”--”);
con.setAutoCommit(false);
—---
—---
—---
con.commit();
}catch(Exception e){
con.rollback();
}

In database applications, if we access more transactions on the single data


item then those transactions are called Concurrent Transactions and that
process is called Transactions concurrency.

In the Transactions concurrency, when we execute more than one transaction on


the single data item then there is a chance to get the following data
inconsistency problems.

1. Lost Update problem


2. Dirty Read Problem
3. Non Repeatable Read problem.
4. Phantom Read Problems.

To resolve all the above problems JDBC has provided Isolation levels.

To provide Isolation property JDBC has provided the following constants in


Connection.

public static final int NONE = 0;


public static final int READ_UNCOMMITTED = 1
public static final int READ_COMMITTED = 2;
public static final int REPEATABLE_READ = 4;
public static final int SERIALIZABLE = 8;

To provide the above isolation levels to the COnnection we have to use the
following method from Connection.

public void setTransactionIsolation(int value)

To get the present isolation value from the COnnection we have to use the
following method.

public int getTransactionIsolation()

All the above isolation levels are able to solve Data inconsistency
problems.

There are two types of Transactions.


1. Local Transactions
2. Global Transactions

Local Transactions are specific to a single transactional resource like a


Jdbc Connection.

Global Transaction requires Multiple transactional resources in a distributed


system.

Transaction Support in Spring:


—-----------------------------
Spring provides a very good Transaction support , it will make the developers
put more focus on the business logic instead of the transaction
configurations ,.....

Spring transaction module is able to provide the following advantages in the


Spring applications.

1. Spring supports declarative transaction management , it uses AOP


internally over the transactional methods to provide data consistency.
2. Spring supports almost all the transaction APIs like JDBC, JPA,
JTA,.....
EX:org.springframework.jdbc.datasource.DriverManagerDataSource for Jdbc
Transactions.
org.springframework.orm.hibernate3.HibernateTransactionManager for ORM tools
like Hibernate.

Spring Framework has provided the following ISOLATION levels in the


predefined class like org.springframework.transaction.TransactionDefinition.

1. ISOLATION_DEFAULT: It is a default isolation level, it will use the


underlying database provided default isolation level.
2. ISOLATION_READ_UNCOMMITTED : It is able to solve the Lost Update
problem, still it is able to represent all the remaining problems.
3. ISOLATION_READ_COMMITTED: It is able to solve the lost update problem
and Dirty Read problem and it is able to represent all the remaining
problems.
4. ISOLATION_REPEATABLE_READ: It is able to solve the Lost Update problem,
Dirty read problem and Non Repeatable Read , still it is able to
represent Phantom Read problem .
5. ISOLATION_SERIALIZABLE: it is able to solve all the data Inconsistency
problems like Lost update, Dirty Read , Non repeatable and Phantom Read
problems.

To set these isolation levels, we have to use the following from


TransactionTemplate :

public void setisolationLevel(TransactionDefinition.ISOLATION_DEFAULT);

Transaction Attributes:
—-----------------------
In an enterprise applications, if a method begins a transaction and access
another method, in this case another method execution is going on the same
translation or in any new transaction is completely depending on the
Transactions Propagation Behavior which we are using in the applications.

Spring Framework has provided very good support for the Propagation behaviors
in the form of the following Constant variables inside the
TransactionDefinition class.

1. PROPAGATION_REQUIRED
2. PRPAGATION_REQUIRES_NEW
3. PROPAGATION_SUPPORTS
4. PROPAGATION_NOT_SUPPORTED
5. PROPAGATION_MANDATORY
6. PROPAGATION_NEVER
7. PROPAGATION_NESTED

To set the above constants in the Spring applications we have to use the
following method from TransactionTemplate.

public void setPropagationBehavior(int value);


EX: txTemplate.setPropagationBehaviour(Transaction
Definition.PROPAGATION_REQUIRES);

PROPAGATION_REQUIRED:
If a method m1 is running a transaction and invokes a method m2 then m2
method will be executed in the same transaction. If the m1() method is not
associated with any Transaction then Container will create a new transaction
to execute method m2.

PROPAGATION_REQUIRES_NEW:
If a method m1 starts a transaction t1 and invokes a method m2, then the
container suspend the current transaction temporarily and creates a new
transaction for m2 method execution, after the m2 method execution method m1
transaction will resume its execution, if m1() method is not associated with
any transaction then container will start a new transaction before starts
m2() method execution.

PROPAGATION_MANDATORY:
If a method m1 is running a transaction and invokes a method m2 the method m2
will be executed in the same transaction. If m1() method is not associated
with any transaction then container will raise an exception like
TransactionThrowsexception

PROPAGATION_SUPPORTS:
If a method m1 starts a transaction and invokes a method m2 then m2() method
will be executed in the same transaction. If the m1() method is not
associated with any transaction then the container does not start a new
Transaction before starting the m2() method.

PROPAGATION_NOT_SUPPORTED:
If a method starts a Transaction and invokes a method m2 then the container
suspends the m1() method transaction before invoking m2() method , when m2()
method execution is completed Container resumes the m1() method transaction .
If the method m1() is not associated with any transaction then Container does
not start a new transaction before executing method m2.

PROPAGATION_NEVER:
If a method m1 starts a transaction and invokes a method m2() then the
Container throws an Exception, if the method m1 is not associated with any
transaction then the container will not start a new transaction for m2
method.

PRPAGATION_NESTED:
It indicates that the method should be run in a nested transaction.

Spring Supported the Transactions in two ways.

1. Programmatic Approach
2. Declarative Approach

Programmatic Approach:
—----------------------
In This approach of transactions, we have to declare the transaction and we
have to perform the transaction commit and rollback operations explicitly by
using java code.

In this approach if we want to provide transactions then we have to use the


following predefined library.

1. TransactionManager:
Transactionmanager is able to define a transaction strategy.

Spring Framework has provided the following TransactionManagers in the form


of the predefined interfaces.

a. DataSourceTransactionManager
b. PlatformTransactionManager
c. HibernateTransactionmanager
d. JTATransactionmanager
—----

In the Transaction based applications we must use either of the above


TransactionManager in the spring configuration file, we musy inject the
Transactionmanager in the DAO.
In general, all the Transaction Managers have the following methods.
1. public TransactionStatus getTransaction(TransactionDefinition txDef)
2. public void commit(TransactionStatus txStatus)
3. public void rollback(TransactionStatus txStatus)

2. TransactionDefinition:
In Transactions, TransactionDefinition is able to provide all the Isolation
levels, Propagation Behaviors, ……

TransactionDefinition has provided the following isolation levels in Spring


applications.

ISOLATION_NONE
ISOLATION_READ_UNCOMMITTED
ISOLATION_READ_COMMITTED
ISOLATION_REPEATABLE_READ
ISOLATION_SERIALIZABLE

TransactionDefinition has the following Propagation behaviors.

PROPAGATION_REQUIRES
PRPOPAGATION_REQUIRES_NEW
PROPAGATION_SUPPORTS
PRPAGATION_NOT_SUPPORTED
PROPAGATION_MANDATORY
PROPAGATION_NESTED
PROPAGATION_NEVER

3. TransactionStatus:
TransactionStatus interface has provided the following methods to control the
Transactions.

1. public boolean isNewTransaction()


2. public boolean hasSavepoint()
3. public void setRollBackOnly()
4. public boolean isRollBackOnly()
5. public void flush()
6. public boolean isCompleted()

EX For Programmatic Approach:


—------------------------------
TransactionDao.java
package com.durgasoft.dao;
public interface TransactionDao {
public String transferFunds(String fromAccount, String toAccount,
int transferAmt);
}

TransactionDaoImpl.java
package com.durgasoft.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import
org.springframework.transaction.support.DefaultTransactionDefinition;

public class TransactionDaoImpl implements TransactionDao{


private JdbcTemplate jdbcTemplate;
private DataSourceTransactionManager dataSourceTransactionManager;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}

public void
setDataSourceTransactionManager(DataSourceTransactionManager
dataSourceTransactionManager) {
this.dataSourceTransactionManager =
dataSourceTransactionManager;
}

@Override
public String transferFunds(String fromAccount, String toAccount,
int transferAmt) {
String status = "";
TransactionDefinition transactionDefinition = new
DefaultTransactionDefinition();
TransactionStatus transactionStatus =
dataSourceTransactionManager.getTransaction(transactionDefinition);
try{
jdbcTemplate.execute("update account set BALANCE = BALANCE
- "+transferAmt+" where ACCNO = '"+fromAccount+"'");
float f = 100/0;
jdbcTemplate.execute("update account set BALANCE = BALANCE
+ "+transferAmt+" where ACCNO = '"+toAccount+"'");
dataSourceTransactionManager.commit(transactionStatus);
status = "Transaction SUCCESS";
}catch (Exception exception){
dataSourceTransactionManager.rollback(transactionStatus);
status = "Transaction FAILURE";
//exception.printStackTrace();
}
return status;
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">
<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>

<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManag
er">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="transactionDao"
class="com.durgasoft.dao.TransactionDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
<property name="dataSourceTransactionManager"
ref="dataSourceTransactionManager"/>
</bean>
</beans>

Main.java
package com.durgasoft;

import com.durgasoft.dao.TransactionDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
TransactionDao transactionDao = (TransactionDao)
applicationContext.getBean("transactionDao");
String status = transactionDao.transferFunds("abc123",
"xyz123", 5000);
System.out.println(status);
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springtxapp01</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.9</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>

</dependencies>
</project>

Drawbacks with Programmatic Approach:


—-------------------------------------------
1. It is suggestible when we have less number of operations in a single
Transaction.
2. It is a somewhat tightly coupled Design.
3. It is not convenient in Enterprise Applications.

Declarative Approach:
—----------------------
IN declarative approach, we will separate transaction Service code and
business logic in spring application, so we are able to get the Loosely
coupled design in Spring applications.
Declarative approach is suggestible when we have more number of operations in
a single transaction.There are two ways to provide transactions in
declarative approach.

1. By Using Transactions namespace tags with AOP implementation.


2. By Using Annotation

By Using Transactions namespace tags with AOP implementation


—--------------------------------------------------------------
To manage Transactions in the declarative approach, the Transactions module
has provided the following tags.

1. <tx:advice>
It represents transaction Advice and it is an implementation of the
TransactionService.

2. <tx:attributes>
It will take transactional methods in order to apply isolation levels
and propagation behaviors.
By using <tx:method> tag

<tx:attributes>
—-----
</tx:attributes>

3. <tx:method>
It is able to define transactional methods and its isolation level and
propagation behavior.

<tx:method name=”--” propagation=”---” isolation=”---”/>

With the above tags we must define transaction advice and it must be
configured with a particular pointcut expression by using <aop:advisor>

EX:
<tx:advice id=”txAdvice” transaction-manager=”txManager”>
<tx:attributes>
<tx:method name=”transferFunds”/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id=”transfer” expression=”execution(*
com.durgasoft.dao.TransactionDao.transferFunds(..))”/>
<aop:advisor pointcut-ref=”transfer” advice-ref=”txAdvice”/>
</aop:config>

EX:
—--
TransactionDao.java
package com.durgasoft.dao;

public interface TransactionDao {


public String transferFunds(String fromAccount, String toAccount,
int transferAmt);
}

TransactionDaoImpl.java
package com.durgasoft.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import
org.springframework.transaction.support.DefaultTransactionDefinition;

public class TransactionDaoImpl implements TransactionDao{


private JdbcTemplate jdbcTemplate;
private DataSourceTransactionManager dataSourceTransactionManager;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}

public void
setDataSourceTransactionManager(DataSourceTransactionManager
dataSourceTransactionManager) {
this.dataSourceTransactionManager =
dataSourceTransactionManager;
}
@Override
public String transferFunds(String fromAccount, String toAccount,
int transferAmt) {
String status = "";
//TransactionDefinition transactionDefinition = new
DefaultTransactionDefinition();
//TransactionStatus transactionStatus =
dataSourceTransactionManager.getTransaction(transactionDefinition);
//try {
int rowCount1 = jdbcTemplate.update("update account set
BALANCE = BALANCE - " + transferAmt + " where ACCNO = '" +
fromAccount + "'");
float f = 100 / 0;
int rowCount2 = jdbcTemplate.update("update account set
BALANCE = BALANCE + " + transferAmt + " where ACCNO = '" + toAccount
+ "'");
//dataSourceTransactionManager.commit(transactionStatus);
if (rowCount1 == 1 && rowCount2 == 1) {
status = "Transaction SUCCESS";
} else {
status = "Transaction FAILURE";
}

//}catch (Exception exception) {

//dataSourceTransactionManager.rollback(transactionStatus);
status = "TRANSACTION FAILURE";
//exception.printStackTrace();
// }
return status;

}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>

<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManag
er">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="transactionDao"
class="com.durgasoft.dao.TransactionDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
<property name="dataSourceTransactionManager"
ref="dataSourceTransactionManager"/>
</bean>
<tx:advice id="txAdvice"
transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<tx:method name="transferFunds"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transfer" expression="execution(*
com.durgasoft.dao.TransactionDao.transferFunds(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="transfer"/>
</aop:config>
</beans>

Main.java
package com.durgasoft;

import com.durgasoft.dao.TransactionDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
TransactionDao transactionDao = (TransactionDao)
applicationContext.getBean("transactionDao");
String status = transactionDao.transferFunds("abc123",
"xyz123", 5000);
System.out.println(status);
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springtxapp01</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-jdbc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.9</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.19</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.19</version>
</dependency>
</dependencies>
</project>

By Using Annotations
—---------------------
This approach is very simple to use in the Transaction Management, in this
approach we will use only @Trasactional annotation just above of the business
methods.

If we want to use @Transactional annotation in Spring applications then we


have to enable the Transactions related annotations, for this we have to use
the following tag in the Spring configuration file.
<tx:annotation-driven transaction-manager=”transactionManager”/>

EX:
TransactionDao.java
package com.durgasoft.dao;

public interface TransactionDao {


public String transferFunds(String fromAccount, String toAccount,
int transferAmt);
}

TransactionDaoImpl.java
package com.durgasoft.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import
org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import
org.springframework.transaction.support.DefaultTransactionDefinition;

public class TransactionDaoImpl implements TransactionDao{


private JdbcTemplate jdbcTemplate;
private DataSourceTransactionManager dataSourceTransactionManager;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}

public void
setDataSourceTransactionManager(DataSourceTransactionManager
dataSourceTransactionManager) {
this.dataSourceTransactionManager =
dataSourceTransactionManager;
}

@Transactional
@Override
public String transferFunds(String fromAccount, String toAccount,
int transferAmt) {
String status = "";
//TransactionDefinition transactionDefinition = new
DefaultTransactionDefinition();
//TransactionStatus transactionStatus =
dataSourceTransactionManager.getTransaction(transactionDefinition);
//try {
int rowCount1 = jdbcTemplate.update("update account set
BALANCE = BALANCE - " + transferAmt + " where ACCNO = '" +
fromAccount + "'");
float f = 100 / 0;
int rowCount2 = jdbcTemplate.update("update account set
BALANCE = BALANCE + " + transferAmt + " where ACCNO = '" + toAccount
+ "'");
//dataSourceTransactionManager.commit(transactionStatus);
System.out.println(rowCount1+","+rowCount2);
if (rowCount1 == 1 && rowCount2 == 1) {
status = "Transaction SUCCESS";
} else {
status = "Transaction FAILURE";
}

//}catch (Exception exception) {

//dataSourceTransactionManager.rollback(transactionStatus);
//status = "TRANSACTION FAILURE";
//exception.printStackTrace();
// }
return status;

}
}
SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<tx:annotation-driven
transaction-manager="dataSourceTransactionManager"/>
<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>

<bean name="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManag
er">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean name="transactionDao"
class="com.durgasoft.dao.TransactionDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
<property name="dataSourceTransactionManager"
ref="dataSourceTransactionManager"/>
</bean>
<!--
<tx:advice id="txAdvice"
transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<tx:method name="transferFunds"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transfer" expression="execution(*
com.durgasoft.dao.TransactionDao.transferFunds(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="transfer"/>
</aop:config>
-->
</beans>
Main.java
package com.durgasoft;

import com.durgasoft.dao.TransactionDao;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
TransactionDao transactionDao = (TransactionDao)
applicationContext.getBean("transactionDao");
String status = transactionDao.transferFunds("abc123",
"xyz123", 5000);
System.out.println(status);
}
}

=================================================================

You might also like