<p>In this article, we will explore about programmatic transaction management. This means that you have manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.</p>
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<h2><b>Programmatic transaction management</b></h2>
<p>It is usually a good idea only if you have a small number of transactional operations. For example, if you have a web application that require transactions only for certain update operations, you may not want to set up transactional proxies using Spring or any other technology. In this case, using the TransactionTemplate may be a good approach. Being able to set the transaction name explicitly is also something that can only be done using the programmatic approach to transaction management.</p>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;">
<p><span style="color: red; font-size: x-large; text-align: center;"><b>Popular Tutorials</b></span></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/spring-tutorial/"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-spring-boot-a-spring-boot-complete-guide/"><strong>Spring Boot Tutorial</strong> </a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-take-baby-step-to-secure/"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/using-spring-jdbc-framework-chapter-32/"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-hateoas-hypermedia-driven-restful-web-service/"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/microservices-with-spring-boot/"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/jax-rs-web-service-tutorial/"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/hibernate-3-on-baby-steps/"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-batch-process-with-example/"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<p>On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure. When using the Spring Framework, rather than EJB CMT, the configuration cost of declarative transaction management is greatly reduced.</p>
<p>Let us see how above mentioned steps work but before we begin, it is important to have at least one database tables on which we can perform various CRUD operations with the help of transactions. Let us take <b>Employee </b>table, which can be created in MySQL <b>DAVDB </b>database with the following DDL:</p>
</div>
<pre class="highlight">CREATE TABLE Employee( 
 EMPID INT NOT NULL AUTO_INCREMENT, 
 NAME VARCHAR(26) NOT NULL, 
 AGE INT NOT NULL, 
 SALARY BIGINT NOT NULL, 
 PRIMARY KEY (EMPID) 
); 
</pre>
<div id="ads-id" align="center"></div>
<p>1. Create a project with a name <b>SpringTMDemo </b>and create a package<i><b> com.dineshonjava.sdnext</b></i> under the <b>src </b>folder in the created project.</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2012/12/TransactionManagement-1.jpg" border="0" /></div>
<p><b>2.</b> Add required Spring libraries using <b><i>Add User Libs</i> </b>option as explained in the <i>S<b>pring Hello World Example</b></i> chapter.<br />
3<i><b>.</b></i> Add other required libraries <b><i>mysql-connector-java.jar</i></b><br />
4.Create DAO interface <i><b>EmpDAO </b></i>and list down all the required methods. Though it is not required and you can directly write <i><b>EmployeeDaoImpl </b></i>class, but as a good practice, let&#8217;s do it.<br />
<b>EmpDAO.java</b></p>
</div>
<pre class="highlight">package com.dineshonjava.sdnext.dao; 
 
import java.util.List; 
 
import com.dineshonjava.sdnext.domain.Employee; 
 
/** 
 * @author Dinesh Rajput 
 * 
 */ 
public interface EmpDao { 
 
 /** 
 * This is the method to be used to create 
 * a record in the Employee table. 
 */ 
 void create(String name, Integer age, Long salary); 
 /** 
 * This is the method to be used to list down 
 * a record from the Employee table corresponding 
 * to a passed Employee id. 
 */ 
 Employee getEmployee(Integer empid); 
 /** 
 * This is the method to be used to list down 
 * all the records from the Employee table. 
 */ 
 List listEmployees(); 
 /** 
 * This is the method to be used to delete 
 * a record from the Employee table corresponding 
 * to a passed Employee id. 
 */ 
 void delete(Integer empid); 
 /** 
 * This is the method to be used to update 
 * a record into the Employee table. 
 */ 
 void update(Integer empid, Integer age); 
} 
 
</pre>
<p><b>EmployeeDaoImpl.java</b></p>
</div>
<pre class="highlight">package com.dineshonjava.sdnext.dao.impl; 
 
import java.util.List; 
 
import org.springframework.dao.DataAccessException; 
import org.springframework.jdbc.core.support.JdbcDaoSupport; 
import org.springframework.stereotype.Component; 
import org.springframework.transaction.PlatformTransactionManager; 
import org.springframework.transaction.TransactionDefinition; 
import org.springframework.transaction.TransactionStatus; 
import org.springframework.transaction.support.DefaultTransactionDefinition; 
 
import com.dineshonjava.sdnext.dao.EmpDao; 
import com.dineshonjava.sdnext.domain.Employee; 
import com.dineshonjava.sdnext.jdbc.utils.EmployeeMapper; 
 
/** 
 * @author Dinesh Rajput 
 * 
 */ 
@Component 
public class EmployeeDaoImpl extends JdbcDaoSupport implements EmpDao { 
// @Autowired 
// private JdbcTemplate jdbcTemplateObject; 
// 
// /** 
// * @param jdbcTemplateObject the jdbcTemplateObject to set 
// */ 
// public void setJdbcTemplateObject(JdbcTemplate jdbcTemplateObject) { 
// this.jdbcTemplateObject = jdbcTemplateObject; 
// } 
 
private PlatformTransactionManager transactionManage; 
 
 public void setTransactionManager( 
 PlatformTransactionManager transactionManager) { 
 this.transactionManager = transactionManager; 
 } 
 
@Override 
public void create(String name, Integer age, Long salary) { 
 TransactionDefinition def = new DefaultTransactionDefinition(); 
 TransactionStatus status = transactionManager.getTransaction(def); 
try { 
 String SQL = "INSERT INTO Employee (name, age, salary) VALUES (?, ?, ?)"; 
 getJdbcTemplate().update(SQL, new Object[]{name, age, salary} ); 
 transactionManager.commit(status); 
System.out.println("Created Record Name = " + name + " Age = " + age+ " Salary = " + salary); 
 // to simulate the exception. 
 throw new RuntimeException("simulate Error condition") ; 
 } catch (DataAccessException e) { 
 System.out.println("Error in creating record, rolling back"); 
 transactionManager.rollback(status); 
 throw e; 
 } 
} 
 
 @Override 
 public Employee getEmployee(Integer empid) { 
 String SQL = "SELECT * FROM Employee WHERE empid = ?"; 
 Employee employee = (Employee) getJdbcTemplate().queryForObject(SQL, new Object[]{empid}, new EmployeeMapper()); 
 return employee; 
 } 
 
 @Override 
 public List listEmployees() { 
 String SQL = "SELECT * FROM Employee"; 
 List employees = (List) getJdbcTemplate().query(SQL, new EmployeeMapper()); 
 return null; 
 } 
 
 @Override 
 public void delete(Integer empid) { 
 String SQL = "DELETE FROM Employee WHERE empid = ?"; 
 getJdbcTemplate().update(SQL, new Object[]{empid}); 
 System.out.println("Deleted Record with EMPID = " + empid ); 
 } 
 
 @Override 
 public void update(Integer empid, Integer age) { 
 String SQL = "UPDATE Employee SET age = ? WHERE empid = ?"; 
 getJdbcTemplate().update(SQL, new Object[]{age, empid}); 
 System.out.println("Updated Record with EMPID = " + empid ); 
 } 
} 
 
</pre>
<p>5. Create other required Java classes <b>Employee, EmployeeMapper and EmpMainApp</b> under the <i><b>com.dineshonjava.sdnext</b></i> package. You can create rest of the POJO classes if required.<br />
<b>Employee.java</b></p>
</div>
<pre class="highlight">package com.dineshonjava.sdnext.domain; 
 
 
 
/** 
 
 * @author Dinesh Rajput 
 
 * 
 
 */ 
 
public class Employee { 
 
 private int empid; 
 
 private String name; 
 
 private int age; 
 
 private long salary; 
 
 /** 
 
 * @return the empid 
 
 */ 
 
 public int getEmpid() { 
 
 return empid; 
 
 } 
 
 /** 
 
 * @param empid the empid to set 
 
 */ 
 
 public void setEmpid(int empid) { 
 
 this.empid = empid; 
 
 } 
 
 /** 
 
 * @return the name 
 
 */ 
 
 public String getName() { 
 
 return name; 
 
 } 
 
 /** 
 
 * @param name the name to set 
 
 */ 
 
 public void setName(String name) { 
 
 this.name = name; 
 
 } 
 
 /** 
 
 * @return the age 
 
 */ 
 
 public int getAge() { 
 
 return age; 
 
 } 
 
 /** 
 
 * @param age the age to set 
 
 */ 
 
 public void setAge(int age) { 
 
 this.age = age; 
 
 } 
 
 /** 
 
 * @return the salary 
 
 */ 
 
 public long getSalary() { 
 
 return salary; 
 
 } 
 
 /** 
 
 * @param salary the salary to set 
 
 */ 
 
 public void setSalary(long salary) { 
 
 this.salary = salary; 
 
 } 
 
 public String toString(){ 
 
 return "EMPLOYEE{empid- "+this.empid+" name- "+this.name+ 
 
 " age- "+this.age+" salary- "+this.salary+"}"; 
 
 } 
 
} 
 
</pre>
<p><b>EmployeeMapper.java</b></p>
</div>
<pre class="highlight">package com.dineshonjava.sdnext.jdbc.utils; 
 
import java.sql.ResultSet; 
import java.sql.SQLException; 
 
import org.springframework.jdbc.core.RowMapper; 
 
import com.dineshonjava.sdnext.domain.Employee; 
 
/** 
 * @author Dinesh Rajput 
 * 
 */ 
public class EmployeeMapper implements RowMapper { 
 public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { 
 Employee employee = new Employee(); 
 employee.setEmpid(rs.getInt("empid")); 
 employee.setName(rs.getString("name")); 
 employee.setAge(rs.getInt("age")); 
 employee.setSalary(rs.getLong("salary")); 
 return employee; 
 } 
} 
</pre>
<p><b>EmpMainApp.java</b></p>
</div>
<pre class="highlight">package com.dineshonjava.sdnext.main; 
 
import java.util.List; 
 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
import com.dineshonjava.sdnext.dao.EmpDao; 
import com.dineshonjava.sdnext.domain.Employee; 
 
/** 
 * @author Dinesh Rajput 
 * 
 */ 
public class EmpMainApp { 
 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) { 
 ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); 
 EmpDao empDao = (EmpDao) context.getBean("employeeDaoImpl"); 
 
 System.out.println("------Records Creation--------" ); 
 empDao.create("Raaz", 25, 50000l); 
 
 System.out.println("------Listing Multiple Records--------" ); 
 List employees = empDao.listEmployees(); 
 for (Employee employee : employees) { 
 System.out.print(employee); 
 } 
 } 
} 
 
</pre>
<p>6. Create Beans configuration file <b>spring.xml</b> under the src folder.</p>
</div>
<pre class="highlight"><;beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:><br />
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:</p>
<p><b>------Records Creation--------</b><br />
<b>Created Record Name = Raaz Age = 25 Salary = 50000</b></p>
<div style="text-align: center;"><b><;<;</b><b><b><a href="https://dineshonjava.com/2012/12/transaction-management-in-spring.html">Transaction Management</a></b></b><b> |<a href="https://dineshonjava.com/2012/06/spring-30-baby-step-to-learn.html">index</a>| </b><b><b><a href="https://dineshonjava.com/2012/12/using-hibernate-with-spring-chapter-37.html">Using Hibernate with Spring</a></b></b><b></b><b>>;>;</b></div>
</div>
<p> ;</p>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/transaction-management-in-spring/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/declarative-transaction-management/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '628'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…