< Prev
Next >



Spring with JDBC Transaction by Annotation



In this tutorial, we are going to explain how to configure and perform transaction management within the database using Spring Framework with JDBC and Annotations. The transaction management involves managing database transactions such as -



What Spring-JDBC transaction management by Annotation does?


The Spring-JDBC transaction management by Annotation makes sure :






How Spring-JDBC transaction management by Annotation works?


To perform transaction management within the database using Spring Framework with JDBC and Annotations, we need an access to the source code to edit it and add @Transactional Annotation to class and methods involved in performing the transaction operations.




Note :


Before we proceed with the example of database transaction management, we would first need to configure Spring Framework to work with JDBC. To perform this, we will use a very important template class provided by Spring Framework which allows us to perform JDBC operations, named - JDBCTemplate.




Creating the Java class - Customer_Account


We are going to create a java class named Customer within the decodejava package and this class contains - Besides this, we are also going to define a couple of getter and setter methods within this class to set the above mentioned properties of Customer class.


package decodejava;

public class Customer_Account 
{
	int id;
	String name;
	int amount;
	int age;
	
	
	public String getName() 
	{
		return name;
	}
	
	
	public void setName(String name) 
	{
		this.name = name;
	}
	
	
	public int getAmount() {
		return amount;
	}


	public void setAmount(int amount) {
		this.amount = amount;
	}


	public int getAge() 
	{
		return age;
	}
	
	
	public void setAge(int age) 
	{
		this.age = age;
	}
	
	
	public int getId() 
	{
		return id;
	}


	public void setId(int id) 
	{
		this.id = id;
	}

}





Class performing data access operations(DAO) using Spring


Next, we are going to add another Java class named CustomerDAO this class will contain separate methods to perform JDBC operations using methods of Spring Framework template class JDBCTemplate, to perform JDBC queries such as -

Besides the above mentioned database operations, this class will also contain separate methods(headed by @Transactional Annotation) to perform transaction operations such as -

This class is also going to contain a JdbcTemplate property named jdbcTemplate, used to perform JDBC operations using Spring.

This JdbcTemplate property will be assigned a value by the Spring Container using its respective setter methods, when the CustomerDAO bean is created by it using the configuration xml file(to be created in the upcoming section).




package decodejava;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.transaction.annotation.Transactional;


@Transactional
public class CustomerDAO /*extends JdbcDaoSupport*/
{
private JdbcTemplate jdbcTemplate;



	//Creating a table
	public void createTable()
	{
		String query = "create table Customer_Account"
					+ "("
					+ "id int,"
					+ "name varchar(40),"
					+ "amount int,"
					+ "age int"
					+ ")";
		
		jdbcTemplate.execute(query);
	}
	
	
	//Getter for JdbcTemplate
	public JdbcTemplate getJdbcTemplate() 
	{
		return jdbcTemplate;
	}

	
	//Setter for JdbcTemplate
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) 
	{
		this.jdbcTemplate = jdbcTemplate;
	}
	

	
	//Adding a customer
	@Transactional
	public void addCustomer(int id, String name, int amount, int age)
	{
		String query ="insert into Customer_Account values(" + id + ",'" + name + "','" + amount + "'," + age + ")";
		jdbcTemplate.execute(query);
	}
	
	
	//Deleting a customer
	@Transactional
	public void deleteCustomer(int id)
	{
		String query = "delete from Customer_Account where id =" + id ;
		jdbcTemplate.execute(query);
	}
	
	
	//Extracting a count of all the customers
	public int countCustomer()
	{
		String query = "select count(*) from Customer_Account";
		return jdbcTemplate.queryForObject(query, Integer.class);
	}
	
	
	//Getting a List of all customers from database
	public List<Customer_Account> getAllCustomer()
	{
		String query ="select * from Customer_Account";
		return jdbcTemplate.query(query, new ResultSetExtractor<List<Customer_Account>>()
		//Anonymous Inner Class
		{
					
				@Override
				public List<Customer_Account> extractData(ResultSet rs) throws SQLException, DataAccessException
				{
					List<Customer_Account> customers = new ArrayList<Customer_Account>();
					while(rs.next())
					{
						Customer_Account customer = new Customer_Account();
						customer.setId(rs.getInt("id"));
						customer.setName(rs.getString("name"));
						customer.setAmount(rs.getInt("amount"));
						customer.setAge(rs.getInt("age"));
						customers.add(customer);
				}
				return customers;
				}
		});
	}
		
	

	
	@Transactional
	public void depositAmount(int id, int amount)
	{
		getJdbcTemplate().update("update Customer_Account set amount=amount+? where id=?", amount, id);		
	}
	
	
	
	@Transactional
	public void withdrawAmount(int id, int amount)
	{
		getJdbcTemplate().update("update Customer_Account set amount=amount-? where id=?", amount, id);		
	}
}





Adding the Utility class that calls the Spring API


Next, we are going to create another class named - Utility, which is a simple java class.

Utility.java
package decodejava;



import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Utility {

	public static void main(String[] args) 
	{
		ApplicationContext context = new FileSystemXmlApplicationContext("classpath:config.beans.xml");
		CustomerDAO customerDAO = context.getBean("CustomerDAOBean",CustomerDAO.class);
		
		
		System.out.println("Creating a table in database");
		customerDAO.createTable();
		
		
		System.out.println("Adding the customers");
		customerDAO.addCustomer(1, "First Customer", 1000, 23);
		customerDAO.addCustomer(2, "Second Customer", 2000, 27);
		customerDAO.addCustomer(3, "Third Customer", 3000, 21);
		
		
		System.out.println("Getting all the customers from the database");
		List<Customer_Account> allCustomers = customerDAO.getAllCustomer();
		for(Customer_Account cust : allCustomers)
		{
			System.out.println("Customer ID : " + cust.getId());
			System.out.println("Customer Name : " + cust.getName());
			System.out.println("Customer Balance Amount : " + cust.getAmount());
			System.out.println("Customer Age : " + cust.getAge());
			
		}
	
		
		System.out.println("Getting the total count of all the Customers");
		System.out.println("Total Customers : " + customerDAO.countCustomer());
		
		
		System.out.println("Deleting a Customer with id = 2");
		customerDAO.deleteCustomer(2);
		
		System.out.println("Getting the new total count of all the Customers after deleting a customer");
		System.out.println("Total Customers : " + customerDAO.countCustomer());
	
		
		System.out.println("A customer with id = 1, is depositing an amount of 20000");
		customerDAO.depositAmount(1, 20000);
		
		System.out.println("A customer with id = 3, is withdrawing an amount of 500");
		customerDAO.withdrawAmount(3, 500);
		
		
		
		System.out.println("Getting all the customers from the database and their updated amount :");
		List<Customer_Account> allCustomers2 = customerDAO.getAllCustomer();
		for(Customer_Account cust : allCustomers2)
		{
			System.out.println("Customer ID : " + cust.getId());
			System.out.println("Customer Name : " + cust.getName());
			System.out.println("Customer Balance Amount : " + cust.getAmount());
			System.out.println("Customer Age : " + cust.getAge());
			                                                           
		}
		
	}

}


The Utility class uses the ApplicationContext container(an interface) of Spring Framework by creating its instance using its implemented class FileSystemXmlApplicationContext, which loads the configuration xml file - config.beans.xml and does the following -






Adding a configuration file


Next, we are going to add a configuration file to our project. This configuration document is an Extensible Markup Language(XML) file, ending with .xml extension and we are going to name file as config.beans.xml.

In this file, we have configured a CustomerDAO bean with a unique id and with its String property named tableName and JdbcTemplate property named jdbcTemplate. These properties will be assigned a value by the Spring Container using their respective setter methods, when the CustomerDAO bean is created by it using the configuration xml file.


config.beans.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:util="springframework.org/schema/util"
   	   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
       https://www.springframework.org/tx/spring-tx.xsd
       ">
      
<tx:annotation-driven transaction-manager="txnManagerBean" proxy-target-class="true"/>
 
          
<bean id="CustomerDAOBean" class="decodejava.CustomerDAO">
<property name="jdbcTemplate" ref="jdbcTemplateBean"></property>
</bean>


<bean id="jdbcTemplateBean" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSourceBean"></property>
</bean>


<bean id="txnManagerBean" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceBean"></property>
</bean>


<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"></property>
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="username" value="scott"></property>
<property name="password" value="tiger"></property>
</bean>


</beans>



This mapping document has a parent <beans> tag as the root element and its individual child elements, each with a <bean> tag, containing all the attributes such as -




Adding JARs








Directory Structure of Project




The picture above depicts how and where to arrange classes and interfaces comprising this Spring Project, in a specific directory structure.

Project Folder - SpringWithJDBCTransactionByAnnotation is the name of our Project and it is a top-level directory.






Execution


Finally, after executing Utility class, you will get the following output within the Console window. This output shown below, shows how the Utility class has used the ApplicationContext container of Spring Framework to load the configuration xml file - config.beans.xml, access the beans specified in it, instantiate the CustomerDAO class and performs JDBC operations by calling the methods of CustomerDAO class.


JAug 10, 2018 12:29:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@5e91993f: startup date [Fri Aug 10 12:29:26 2018]; root of context hierarchy
Aug 10, 2018 12:29:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config.beans.xml]
Aug 10, 2018 12:29:31 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: oracle.jdbc.driver.OracleDriver
Creating a table in database
Adding the customers
Getting all the customers from the database
Customer ID : 1
Customer Name : First Customer
Customer Balance Amount : 1000
Customer Age : 23
Customer ID : 2
Customer Name : Second Customer
Customer Balance Amount : 2000
Customer Age : 27
Customer ID : 3
Customer Name : Third Customer
Customer Balance Amount : 3000
Customer Age : 21
Getting the total count of all the Customers
Total Customers : 3
Deleting a Customer with id = 2
Getting the new total count of all the Customers after deleting a customer
Total Customers : 2
A customer with id = 1, is depositing an amount of 20000
A customer with id = 3, is withdrawing an amount of 500
Getting all the customers from the database and their updated amount :
Customer ID : 1
Customer Name : First Customer
Customer Balance Amount : 21000
Customer Age : 23
Customer ID : 3
Customer Name : Third Customer
Customer Balance Amount : 2500
Customer Age : 21


And, this concludes performing transaction management by configuring Spring Framework with JDBC using Annotations.




Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter



< Prev
Next >
< Spring-JDBC Programmatic TS
Spring-JDBC TS by Schema >

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page

Notifications



Please check our latest addition

PYTHON