Nearby lessons

17 of 35

Spring - Transaction Management

📌 What You Will Learn
  • Understand Spring - Transaction Management
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Transaction Management step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Transaction Management

Transaction is an unit of work performed by Front End applications on 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 ACID properties

  • Atomicity: This property will make the Transaction either in SUCCESS state or in FAILURE state.

In Database related applications, if we perform all operations then the Transaction is available in SUCCESS State, if we perform none of the operations then the Transaction is available in FAILURE state.

  • Consistency:In database applications, Before the Transaction and After the Transaction Database state must be in stable.
  • Isolation: If we run more than one Transaction on a single Data item then that Transactions are called as "Concurret Transactions". In Transactions Concurrency , one transaction execution must not give effect to another Transaction, this rule is called as "Isolation" property.
  • Durability: After committing the Transaction, if any failures are coming like Power failure, OS failure,... after getting the System if we open the transaction then the modifications which we performed during the transaction must be preserved.

In JDBC, to perform Automicity property we have to change Connections auto-commit nature and we have to perform either commit() or rollback() at the end of Transaction.

Example01
JCode Cell
1 
2Connection con = DriverManager.getConnection(---);
3con.setAutoCommit(false);
4try{
5---instructions-----
6con.commit();
7}catch(Exception e){
8e.printStacktrace();
9con.rollback();
10}
11

Transaction Management

In Hibernate applications, if we want to manage Transactions Automicity property then we have to use the following steps.

  • Declare Transaction Before try.
  • Create Transaction object inside try block.
  • Perform commit() operation at end of Transaction.
  • Perform rollback() operation at catch block.

Transaction tx = null;

  • try{
  • tx = session.beginTransaction();
  • tx.commit();
  • }catch(Exception e){
  • tx.rollback();

If we execute more than one transaction on a single data item then that transactions are called as Concurrent Transactions.

In Transactions concurrency we are able to get the following data consistency problems while executing more than one transaction at a time.

  • Lost Update Problem
  • Dirty Read Problem
  • Non Repeatable Read Problem
  • Phanthom Read Problem

Lost Update Problem

In Transactions concurrency, if one transaction perform updations over the data with out commit operation , mean while, other transactions perform updations with commit operation then the first transaction updations are lost, this data consistency problem is called as Lost Update problem.

Dirty Read Problem

In Transactions concurrency, if one transaction perform updations over data with out performing commit / rollback, mean while if other Transaction perform Read operation over the uncommitted data with out performing commit/rollback operations, in this context, if first transaction perform Rollback operation then the read operation performed by second transaction is Dirty Read, this problem is called as Dirty Read problem.

Non Repeatable Read Problem

In Transactions concurrency, One transaction perform continous read operations to get same results, mean while, between two read operations another transaction performs update operation over the same data, in this context, in the next read operation performed by first transaction may not get same repeatable results, this problem is called as Non Repeatable Read Problem.

Phantom Read Problem

In Transactions concurrency, one transaction perform read operation continously to get same no of results at each and every read operation , mean while, other transactions may perform insert operations between two read operations performed by first transactions, in this context, in the next read operation performed by first transaction may not generate the same no of results, this problem is called as "Panthom Read" Problem, here the extra records inserted by second transaction are called as "Panthom Records".

  • public sttaic final int TRANSCATION_NONE = 0;
  • public sttaic final int TRANSCATION_READ_UNCOMMITTED = 1;
  • public sttaic final int TRANSCATION_READ_COMMITTED = 2;
  • public sttaic final int TRANSCATION_REPETABLE_READ = 4;
  • public sttaic final int TRANSCATION_SERIALIZABLE = 8;

public void setTransactionIsolation(int isolation_Level) EX: con.setTransactionIsolation(Connection.TRANSACTION_READ_

COMMITTED); <property name="hibernate.connection.isolation>val</property> Where value may be either of the following Constants NONE = 0; READ_UNCOMMITTED = 1; READ_COMMITTED = 2; REPEATABLE_READ = 4; SERIALIZABLE = 8;

Example06
JCode Cell
1 
2<hibernate-configuration>
3<session-factory>
4----
5<property name="hibernate.connection.isolation>
6 SERIALIZABLE
7</property>
8-----
9</session-factory>
10</hibernate-configuration>
11

There are two types of Transactions

  • Local Transaction
  • Global Transaction

Local Transaction

Local transactions are specific to a single transactional resource like a JDBC connection

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

Global transactions can span multiple transactional resources like transaction in a distributed system

Global transaction management is required in a distributed computing environment where all the resources are distributed across multiple systems

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.

Transaction Support in Spring

Spring provides extensive support for transaction management and help developers to focus more on business logic rather than worrying about the integrity of data incase of any system failures. Spring Transaction Management is providing the following advantages in enterprise applications:

  • Spring Supports Declarative Transaction Management. In this model, Spring uses AOP over the transactional methods to provide data integrity. This is the preferred approach and works in most of the cases.
  • Spring Supports most of the transaction APIs such as JDBC, Hibernate, JPA, JDO, JTA etc. All we need to do is use proper transaction manager implementation class.

EX:

 org.springframework.jdbc.datasource.DriverManagerDataSource for JDBC transaction management  org.springframework.orm.hibernate3.HibernateTransactionManager for Hibernate as ORM tool.  Support for programmatic transaction management by using TransactionTemplate or PlatformTransactionManager implementation.

To represent ISOLATION levels Spring Framework has provided the following Constants from "org.springframework.transaction .TransactionDefinition".

  • ISOLATION_DEFAULT: It is default isolation level, it will use the underlying database provided default Isolation level.
  • ISOLATION_READ_UNCOMMITTED: It will not resolve any ISOLATION problem, It represents dirty read problem, non-repeatable read problem, phantom read problem .
  • ISOLATION_READ_COMMITTED: It will resolve dirty read problem,but, it will represent non-repeatable read problem and phantom read problem.
  • ISOLATION_REPEATABLE_READ: It will resolve dirty read problem and non-repeatable read problem , but, It will represent phantom read problem.
  • ISOLATION_SERIALIZABLE: It will resolve all ISOLATION problems like dirty reads, non- repeatable read, and phantom read Problems.

To set the above Isolation level to TransactionTemplate then we have to use the following method .public void setIsolationLevel(int value) EX: txTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT); Transaction Attributes

In Enterprise applications, if we a method begins a transaction and access another method, in this context, another method execution is going on in the same Transaction or in any new Transaction is completely depending on the Transaction Propagation behaviour what we are using.

Spring Framewrk has provided very good suport for Propagation Behaviour in the form of the following constants from "org.springframework.transaction .TransactionDefinition".

  • PROPAGATION_REQUIRED
  • PROPAGATION_REQUIRES_NEW
  • PROPAGATION_SUPPORTS
  • PROPAGATION_NOT_SUPPORTED
  • PROPAGATION_MANDATORY
  • PROPAGATION_NEVER
  • PROPAGATION_NESTED

PROPAGATION_REQUIRED

If a method1 is running in a transaction and invokes method2 then method2 will be executed in the same transaction. If method1 is not associated with any Transaction then Container will create new Transaction to execute Method2.

PROPAGATION_REQUIRES_NEW

If a method1 is running in a transaction and invokes method2 then container will suspend the current Transaction temporarily and creates new Transaction for method2. After executing method2 transaction then method1 transaction will continue.If Method1 is not associated with any transaction then container will start a new transaction before starts new method.

PROPAGATION_MANDATORY

If a method1 is running in a transaction and invokes method2 then method2 will be executed in the same transaction. If method1 is not associated with any Transaction then Container will raise an exception like "TransactionThrowsException".

PROPAGATION_SUPPORTS

If a method1 is running in a transaction and invokes method2 then method2 will be executed in the same transaction. If method1 is not associated with any Transaction then Container does not start new Transaction before running method2.

PROPAGATION_NOT_SUPPORTED

If a method1 is running in a transaction and invokes method2 then Container Suspends the Mehod1 transaction before invoking Method2. When Method2 has completed , container resumes Method1 transaction. If Mehod1 is not associated with Tramsaction then Container does not start new Tansaction before executing Method2.

PROPAGATION_NEVER

If a method1 is running in a transaction and invokes method2 then Container throws an Exception like RemoteException. I mthod1 is not associated with any transaction then Container will not start new Transaction for Method2.

PROPAGATION_NESTED

Indicates that the method should be run with in a nested transaction if an existed transaction is in progress.

To set the above Propagation Behaviout to TransactionTemplate then we have to use the following method.

public void setPropagationBehaviour(int value)

EX:

txTemplate.setPropagationBehaviour(TransactionDefinition.PROPAGATION_EQUIRES_NEW); Transactions Approaches in Spring

Spring Framework supports Transactions in two ways.

  • Programmatic Approach
  • Declarative Approach

Programmetic Approach

In Programatic Approach of transactions we have to declare the transaction and we have to perform transactions commit or rollback operations explicitly by using JAVA code.

In Programetic approach if we want to provide transactions then we have to use the following predefined Library.

Transaction Manager

The main intention of TransactionManager is is able to define a Transaction Strategy in spring application.

Spring Framework has provided Transaction manager in the form of a predefined interfaces

  • org.springframework.jdbc.datasource.DataSourceTransactionManager
  • org.springframework.transaction.PlatformTransactionManager
  • org.springframework.orm.hibernate4.HibernateTransactionManager
  • org.springframework.transaction.jta.JtaTransactionManager

In Spring Transaction based applicatins , We must configure either of the above TransactionManager in configuration file and we must inject TransactionManager in DAO implementation class.

DataSourceTransactionManager includes the following methods to manage transaction.

  • public TransactionStatus getTransaction(TransactionDefinition tx_Def)
  • public void commit(TransactionStatus tx_Status)
  • public void rollback(TransactionStatus tx_Status)

TransactionDefinition

org.springframework.transaction.TransactionDefinition is able to specify ISOLATION levels, Propagation behaviours, Transactions Time out and Transactions Read Only status,.....

TransactionDefinition includes the following Constants to manage Transactions ISOLATION Levels in Spring applications.

  • ISOLATION_READ_UNCOMMITTED
  • ISOLATION_READ_COMMITTED
  • ISOLATION_REPEATABLE_READ
  • ISOLATION_SERIALIZABLE

TransactionDefinition includes the following Constants to manage Transactions Propagation Behaviours in Spring applications.

  • PROPAGATION_REQUIRED
  • PROPAGATION_REQUIRES_NEW
  • PROPAGATION_SUPPORTS
  • PROPAGATION_NOT_SUPPORTED
  • PROPAGATION_MANDATORY
  • PROPAGATION_NESTED
  • PROPAGATION_NEVER

TransactionStatus

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

TransactionStatus includes the following methods to manage Transactions in Spring applications.

  • public boolean isNewTransaction()
  • boolean hasSavepoint()
  • public void setRollbackOnly()
  • public boolean isRollbackOnly()
  • public void flush()
  • public boolean isCompleted()

Example on Spring Transactions in Programmetic Approach — TransactionDao.java

Example22
JCode Cell
1 
2package com.durgasoft.dao;
3public interface TransactionDao {
4public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
5}
6

Example on Spring Transactions in Programmetic Approach — TransactionDaoImpl.java

Example23
JCode Cell
1 
2package com.durgasoft.dao;
3import org.springframework.jdbc.core.JdbcTemplate;
4import org.springframework.jdbc.datasource.DataSourceTransactionManager;
5import org.springframework.transaction.TransactionDefinition;
6import org.springframework.transaction.TransactionStatus;
7import org.springframework.transaction.support.DefaultTransactionDefinition;
8 
9public class TransactionDaoImpl implements TransactionDao {
10 
11private JdbcTemplate jdbcTemplate;
12private DataSourceTransactionManager transactionManager;
13 
14public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
15this.jdbcTemplate = jdbcTemplate;
16}
17public void setTransactionManager(DataSourceTransactionManager transactionManager) {
18this.transactionManager = transactionManager;
19}
20 
21@Override
22public String transferFunds(String fromAccount, String toAccount, int transfer_Amt) {
23String status = "";
24TransactionDefinition tx_Def = new DefaultTransactionDefinition();
25TransactionStatus tx_Status = transactionManager.getTransaction(tx_Def);
26try {
27 withdraw(fromAccount, transfer_Amt);
28 deposit(toAccount, transfer_Amt);
29 transactionManager.commit(tx_Status);
30 status = "Transaction Success";
31 
32} catch (Exception e) {
33 transactionManager.rollback(tx_Status);
34 status = "Transaction Failure";
35 e.printStackTrace();
36}
37return status;
38}
39public void withdraw(String acc, int wd_Amt) {
40 
41 jdbcTemplate.execute("update account set BALANCE = BALANCE -"+wd_Amt+" where ACCNO = '"+acc+"'");
42 
43 
44}
45public void deposit(String acc, int dep_Amt)throws Exception {
46 
47 float f = 100/0;
48 jdbcTemplate.execute("update account set BALANCE = BALANCE + "+dep_Amt+" where ACCNO = '"+acc+"'");
49 
50}
51}
52

Example on Spring Transactions in Programmetic Approach — applicationContext.xml

Example24
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:context="http://www.springframework.org/schema/context"
6xsi:schemaLocation="
7 http://www.springframework.org/schema/beans
8 http://www.springframework.org/schema/beans/spring-beans.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context.xsd">
11<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
12<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
13<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
14<property name="username" value="system"/>
15<property name="password" value="durga"/>
16</bean>
17<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
18<property name="dataSource" ref="dataSource"/>
19</bean>
20<bean id="transactionDao" class="com.durgasoft.dao.TransactionDaoImpl">
21<property name="jdbcTemplate" ref="jdbcTemplate"/>
22<property name="transactionManager" ref="transactionManager"/>
23</bean>
24<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
25<property name="dataSource" ref="dataSource"/>
26</bean>
27 
28</beans>
29

Example on Spring Transactions in Programmetic Approach — Test.java

Example25
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.dao.TransactionDao;
8 
9public class Test {
10 
11public static void main(String[] args) {
12ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
13TransactionDao tx_Dao = (TransactionDao)context.getBean("transactionDao");
14String status = tx_Dao.transferFunds("abc123", "xyz123", 5000);
15System.out.println(status);
16}
17}
18

Drawbacks with Transactions Programatic Approach

  • Programatic Approach is suggestible when we have less no of operations in Transactions, it is not suggestible when we have more no of operations in Transactions.
  • Programatic Approach is some what tightly coupled approach , because, it includes both Business logic and Transactions service code as a single unit.
  • Programatic approach is not convenient to use in enterprise Applications.

Declarative Approach

In Declarative approach, we will seperate Transaction Service code and Business Logic in Spring applications , so that, we are able to get loosly coupled design in Spring applications.

Declarative approach ios suggestible when we have more no of operations in Transactions.

Declarative approach is not convenient to use in enterprise Applications because of AOP.

There are two ways to provide Transaction management in declarative approach.

  • Using Transactions Namespace Tags with AOP implementation
  • Using Annotations.

Using Transactions Namespace Tags with AOP implementation

To manage Transactions in declarative approach, Spring Transaction module has provided the following AOP implemented tags.

  • <tx:advice>

It represent Transaction Advice, it is the implementation of Transaction Service.

Syntax:

<tx:advice id=‖---― transaction-manager=‖----―>
  • <tx:attributes>

It will take Transactional methods inorder to apply Isolation levels and Propagation behaviours,...... by using <tx:method> tag.

Syntax:

<tx:attributes> -----
<tx:attributes>
  • <tx:method>

It will define Transactional method and its propagation Behaviours, Isolation levels, Timeout statuses,....

Syntax:

<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> tag.

Example28
JCode Cell
1 
2<tx:advice id="txAdvice" transaction-manager="transactionManager">
3<tx:attributes>
4<tx:method name="transferFunds"/>
5</tx:attributes>
6</tx:advice>
7<aop:config>
8<aop:pointcut expression="execution(* com.durgasoft.dao.TransactionDao.transferFunds(..))" id="transfer"/>
9<aop:advisor pointcut-ref="transfer" advice-ref="txAdvice"/>
10</aop:config>
11

Example on Spring Transactions in Declarative Approach with XML Configuration — TransactionDao.java

Example29
JCode Cell
1 
2package com.durgasoft.dao;
3public interface TransactionDao {
4public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
5}
6

Example on Spring Transactions in Declarative Approach with XML Configuration — TransactionDaoImpl.java

Example30
JCode Cell
1 
2package com.durgasoft.dao;
3import org.springframework.jdbc.core.JdbcTemplate;
4import org.springframework.jdbc.datasource.DataSourceTransactionManager;
5import org.springframework.transaction.TransactionDefinition;
6import org.springframework.transaction.TransactionStatus;
7import org.springframework.transaction.support.DefaultTransactionDefinition;
8 
9 
10public class TransactionDaoImpl implements TransactionDao {
11 
12private JdbcTemplate jdbcTemplate;
13public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
14this.jdbcTemplate = jdbcTemplate;
15}
16@Override
17public String transferFunds(String fromAccount, String toAccount, int transfer_Amt) {
18String status = "";
19 int val1 = jdbcTemplate.update("update account set BALANCE = BALANCE -"+transfer_Amt+" where ACCNO = '"+fromAccount+"'");
20 float f = 100/0;
21 int val2 = jdbcTemplate.update("update account set BALANCE = BALANCE + "+transfer_Amt+" where ACCNO = '"+toAccount+"'");
22 if(val1 ==1 && val2 ==1) {
23 status = "Transaction Success";
24 }else {
25 status = "Transaction Failure";
26 }
27return status;
28}
29}
30

Example on Spring Transactions in Declarative Approach with XML Configuration — ApplicationContext.xml

Example31
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xmlns:tx="http://www.springframework.org/schema/tx"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/tx
11http://www.springframework.org/schema/tx/spring-tx.xsd
12http://www.springframework.org/schema/aop
13http://www.springframework.org/schema/aop/spring-aop.xsd">
14 
15 
16<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
17<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
18<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
19<property name="username" value="system"/>
20<property name="password" value="durga"/>
21</bean>
22<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
23<property name="dataSource" ref="dataSource"/>
24</bean>
25<bean id="transactionDao" class="com.durgasoft.dao.TransactionDaoImpl">
26<property name="jdbcTemplate" ref="jdbcTemplate"/>
27</bean>
28<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
29<property name="dataSource" ref="dataSource"/>
30</bean>
31 
32<tx:advice id="txAdvice" transaction-manager="transactionManager">
33<tx:attributes>
34 <tx:method name="transferFunds"/>
35</tx:attributes>
36</tx:advice>
37<aop:config>
38<aop:pointcut expression="execution(* com.durgasoft.dao.TransactionDao.transferFunds(..))" id="transfer"/>
39<aop:advisor pointcut-ref="transfer" advice-ref="txAdvice"/>
40</aop:config>
41 
42</beans>
43

Example on Spring Transactions in Declarative Approach with XML Configuration — Test.java

Example32
JCode Cell
1 
2package com.durgasoft.test;
3import org.springframework.context.ApplicationContext;
4import org.springframework.context.support.ClassPathXmlApplicationContext;
5 
6import com.durgasoft.dao.TransactionDao;
7 
8public class Test {
9 
10public static void main(String[] args) {
11ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
12TransactionDao tx_Dao = (TransactionDao)context.getBean("transactionDao");
13String status = tx_Dao.transferFunds("abc123", "xyz123", 100);
14System.out.println(status);
15}
16}
17

Using Annotations

This approach is very simple to use for transactions in Spriong applications. In this approach, we will use @Transactional annotation just before the transactional methods in DAO implementation classes, but, to use this annotation we must activate @Transactional annotation in Spring configuration file vy using the following tag.

<tx:annotation-driven transaction-manager="transactionManager"/>

Example on Spring Transactions in Declarative Approach with Annotations — TransactionDao.java

Example34
JCode Cell
1 
2package com.durgasoft.dao;
3public interface TransactionDao {
4public String transferFunds(String fromAccount, String toAccount, int transfer_Amt);
5}
6

Example on Spring Transactions in Declarative Approach with Annotations — TransactionDaoImpl.java

Example35
JCode Cell
1 
2package com.durgasoft.dao;
3import org.springframework.jdbc.core.JdbcTemplate;
4import org.springframework.jdbc.datasource.DataSourceTransactionManager;
5import org.springframework.transaction.TransactionDefinition;
6import org.springframework.transaction.TransactionStatus;
7import org.springframework.transaction.annotation.Transactional;
8import org.springframework.transaction.support.DefaultTransactionDefinition;
9 
10 
11public class TransactionDaoImpl implements TransactionDao {
12 
13private JdbcTemplate jdbcTemplate;
14public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
15this.jdbcTemplate = jdbcTemplate;
16}
17 
18@Transactional
19@Override
20public String transferFunds(String fromAccount, String toAccount, int transfer_Amt) {
21String status = "";
22 int val1 = jdbcTemplate.update("update account set BALANCE = BALANCE -"+transfer_Amt+" where ACCNO = '"+fromAccount+"'");
23 float f = 100/0;
24 int val2 = jdbcTemplate.update("update account set BALANCE = BALANCE + "+transfer_Amt+" where ACCNO = '"+toAccount+"'");
25 if(val1 ==1 && val2 ==1) {
26 status = "Transaction Success";
27 }else {
28 status = "Transaction Failure";
29 }
30return status;
31}
32}
33

Example on Spring Transactions in Declarative Approach with Annotations — ApplicationContext.xml

Example36
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xmlns:tx="http://www.springframework.org/schema/tx"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/tx
11http://www.springframework.org/schema/tx/spring-tx.xsd
12http://www.springframework.org/schema/aop
13http://www.springframework.org/schema/aop/spring-aop.xsd">
14 
15<tx:annotation-driven transaction-manager="transactionManager"/>
16<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
17<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
18<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
19<property name="username" value="system"/>
20<property name="password" value="durga"/>
21</bean>
22<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
23<property name="dataSource" ref="dataSource"/>
24</bean>
25<bean id="transactionDao" class="com.durgasoft.dao.TransactionDaoImpl">
26<property name="jdbcTemplate" ref="jdbcTemplate"/>
27</bean>
28<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
29<property name="dataSource" ref="dataSource"/>
30</bean>
31 
32 
33</beans>
34

Example on Spring Transactions in Declarative Approach with Annotations — Test.java

Example37
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.dao.TransactionDao;
8 
9public class Test {
10 
11public static void main(String[] args) {
12ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
13TransactionDao tx_Dao = (TransactionDao)context.getBean("transactionDao");
14String status = tx_Dao.transferFunds("abc123", "xyz123", 100);
15System.out.println(status);
16}
17}
18

Introduction

The main intention of Spring WEB MVC module is to prepare web applications with MVC design patterns.

Q)To prepare web applications we have already Struts1 Framework then what is the requirement to use Spring Web MVC Module?

Ans

  • Struts is Web Framework, it able to provide very good environment to prepare and execute web applications.

Spring Framework is an application Framework, it able to provide very good environment to prepare any type of application like Standalone applications, web applications, Distributed applications,.....

  • Struts framework is mainly MVC based frame work, it able to use only MVC and its corelated design pattern.

In Spring framework, only Web Module is able to use MVC Design Pattern.

  • Struts Framework is heavy weight Framework.

Spring Framework is light weight Framework.

  • Struts framework is able to provide tightly coupled design for its applications.

Spring framework is able to provide loosly coupled design.

  • Struts is not providing clear seperatin between Controller layer, Beans Model and View part.

Spring Framework is able to provide clear seperation between controller layer, Model and View part.

  • Struts is more API dependent, it is very difficult to perform debugging and Testing.

Spring is less API dependent, it is very simple perform debugging and testing.

  • Struts is not providing very good environment to integrate other technology applications like JDBC, Hibernate, EJBs,....

Spring is providing very good environment to integrate other technology applications like JDBC, Hibernate,...

  • Struts is able to use only HTML, JSP ,... basic view related tech to prepare View part.

Spring is able to provide very good environment to use view related tech like HTML, JSP, velocity, Freemarker,.....

  • Struts is not having AOP implementations to provide loosly coupled design.

Spring is supporting AOP implementations to provide loosly coupled design.

  • Struts is not layered/Modularized Framework.

Spring is layered/Modularization Framework.

  • Struts is said to be invasive. In Struts we used to extend Action Classes and ActionForm classes.It forces the programmer that, the programmer class must extend from the base class provided by Struts API.

Spring Framework is said to be a non-invasive means it doesn‘t force a programmer to extend or implement their class from any predefined class or interface given by Spring API.

  • Struts framework is able to provide very good Tag library to prepare view part.

Spring framework is not providing good tag library to prepare view part.

  • Spring is providing very good Transaction management and Messaging support for its applications.

Struts is not providing support for Transaction Management and Messaging Support.

Q)To prepare MVC Based Web Applications we have already JSF[Java Server Faces] then what is the requirement to use Spring Web MVC Framework?

Ans

  • JSF is web framework, it able to provide environment to prepare web applications only.

Spring Framework is an application Framework, it able to provide very good environment to prepare any type of application like Standalone applications, web applications, Distributed applications,.....

  • JSF is Component based Framework, for every view , JSF will create a Component Tree

inorder to manage data.

Spring Framework is not Component based Framework, it will use Beans to manage Form data.

  • JSF is View layered Framework, It will focus on View Layer.

Spring is not View Layered Framework, it will focus on all layers of tghe Enterprise Applications.

  • JSF is having very good Convertors , Validations and Rendering Mechanisms.

Spring is not having good Convertors, validations and Renderring Mechanisms.

  • JSF is having inbilt AJAX suppoort.

Spring is not having inbuilt Ajax support.

  • JSF is not having Middleware Services support like Transactions, Messaging, ....

Spring is having very good support for Transactions, Messaging,....

  • JSF is not having any integration environment to integrate other technologies applications like JDBC, EJBs, RMI,....

Spring is providing very good environment to integrate other technologies applications like JDBC, EJBs, Hibernate, Struts,.....

  • JSF is not having very good Security implementations.

Spring is having a seperate Security module to provide security.

Spring Web MVC Features

  • Spring Web MVC contains no of components like controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, and so on , Each and every component has its own roles and responsibilities.
  • Spring framework allows Powerful and straightforward configuration of both framework and application classes as JavaBeans. This configuration capability includes easy navidation across contexts, such as from web controllers to business objects and validators.
  • Spring Framework is allowing Command and Form objects to reuse Business code instead of extending Frameworks provided API libraries.
📝 Key Takeaways
  • Key ideas of Spring - Transaction Management explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end