Friday, 12 September 2014

Spring Transaction

Just Small project done for testing Spring Transaction. For future reference I am writing this Blog.

Web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringSecurity</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
   <servlet-name>spring-security</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>spring-security</servlet-name>
   <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
 
        <!-- Loads Spring Security config file -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   /WEB-INF/spring-security-servlet.xml
  </param-value>
 </context-param>
 
</web-app>



spring-security-servlet.xml

 

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
 
 <context:component-scan base-package="com.prajith.*" />
 
 <bean
   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="prefix">
  <value>/view/</value>
   </property>
   <property name="suffix">
  <value>.jsp</value>
   </property>
 </bean>
   
    <!-- Initialization for data source -->
   <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/maverick"/>
      <property name="username" value="root"/>
      <property name="password" value="*******"/>
   </bean>

   <!-- Initialization for TransactionManager -->
   <bean id="transactionManager" 
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource"  ref="dataSource" />    
   </bean>
 
  <!-- enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="transactionManager"/><!-- a PlatformTransactionManager is still required -->
</beans>

For making annotation driven need to add the code.
<tx:annotation-driven transaction-manager="transactionManager"/>

Transaction manager changes with the interacting platform.

Platform                     TransactionManager or PlatFormTransactionManager
 JDBC                         org.springframework.jdbc.datasource.DataSourceTransactionManager
 JTA                            org.springframework.transaction.jta.JtaTransactionManager 

 Hibernate                    org.springframework.orm.hibernate3.HibernateTransactionManager

 

Types of Probagation defined in the Spring Docs










MANDATORY :Support a current transaction, throw an exception if none exists.
NESTED :Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER :Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED : Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED : Support a current transaction, create a new one if none exists.
REQUIRES_NEW : Create a new transaction, suspend the current transaction if one exists.
SUPPORTS : Support a current transaction, execute non-transactionally if none exists. 

SpringTransactionTest.java 

package com.prajith.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.prajith.web.service.EmployeeServiceIntf;

@Controller
public class SpringTransactionTest {

 @Autowired
 EmployeeServiceIntf employeeServiceIntf;
 
 public void setEmployeeServiceIntf(EmployeeServiceIntf employeeServiceIntf) {
  this.employeeServiceIntf = employeeServiceIntf;
 }
 
 @RequestMapping(value="/sqltransactionTest")
 public ModelAndView testTransaction(){
  ModelAndView model= new ModelAndView("admin");
  try{
   employeeServiceIntf.testTransaction(); 
  }catch(Exception e){
   System.out.println(e);
  }
  return model;
 }
}



EmployeeServiceIntf.java


package com.prajith.web.service;

public interface EmployeeServiceIntf {
 public void testTransaction() throws Exception;
}
 

EmployeeServiceImpl.java
 

package com.prajith.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.prajith.web.dao.EmployeeDAOIntf;
import com.prajith.web.domain.Employee;
import com.prajith.web.domain.Salary;

@Service
public class EmployeeServiceImpl implements EmployeeServiceIntf {

 @Autowired
 private EmployeeDAOIntf employeeDAOIntf;
 
 public void setEmployeeDAOIntf(EmployeeDAOIntf employeeDAOIntf) {
  this.employeeDAOIntf = employeeDAOIntf;
 }

 @Transactional// autoscan makes this method transactional
 public void testTransaction() throws Exception {
  // TODO Auto-generated method stub
  
  Employee emp=new Employee();
  emp.setEmpName("prajith");
  
  Salary sal =new Salary();
  sal.setEmpNo(1);
  sal.setSalary(20000);
  employeeDAOIntf.insertEmp(emp);
  employeeDAOIntf.insertSalary(sal);
  
  Employee emp1=new Employee();
  emp1.setEmpName("pooja");
  
  Salary sal1 =new Salary();
  sal1.setEmpNo(3);//purposefully kept so that DB will throw error.
  sal1.setSalary(204440);
  employeeDAOIntf.insertEmp(emp1);
  employeeDAOIntf.insertSalary(sal1);
 }

}



EmployeeDAOIntf
 

package com.prajith.web.dao;

import com.prajith.web.domain.Employee;
import com.prajith.web.domain.Salary;

public interface EmployeeDAOIntf {
 public void insertEmp(Employee emp) throws Exception;
 public void insertSalary(Salary emp) throws Exception;
}


EmployeeDAOImpl


package com.prajith.web.dao;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.prajith.web.domain.Employee;
import com.prajith.web.domain.Salary;

@Repository
public class EmployeeDAOImpl implements EmployeeDAOIntf{

 String sql1 = "insert into Employee (empname) values (?)";
 String sql2 = "insert into Salary (empid, Salary) values (?, ?)";
 @Autowired
 private DataSource dataSource;
 
 public DataSource getDataSource() {
  return dataSource;
 }

 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }

 public void insertEmp(Employee emp) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("Employee Insertion");
  JdbcTemplate jt=new JdbcTemplate(dataSource);
  jt.update(sql1,emp.getEmpName());
  System.out.println("--> Employee data inserted : " );
 }

 public void insertSalary(Salary sal) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("Salary Insertion");
  JdbcTemplate jt=new JdbcTemplate(dataSource);
  jt.update(sql2,sal.getEmpNo(),sal.getSalary());
  System.out.println("salary inserted successfully : ");
 }

}