Sunday, February 16, 2014

How to maintain Transaction Management in hibernate using Spring HibernateTransactionManager ?

StudentController.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jl.controllers;

import org.jl.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author Rishitha
 */
@Controller
public class StudentController {

    @Autowired
    StudentService regService;
    @Autowired
    HibernateTransactionManager ptm;

    @RequestMapping("/studentReg.spring")

    String saveStudentRegDetails(StudentTo st) {
        TransactionStatus td = ptm.getTransaction(new DefaultTransactionDefinition());

        try {
            //This calls dao and tries
            //to insert student details in to 2 tables
            //student
            regService.registerStudent(st);
        } catch (Exception e) {
            ptm.rollback(td);
            return "failure";
        }
        ptm.commit(td);
        return "success";

    }

}

2)StudentTo.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.controllers;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author Rishitha
 */
@Entity
@Table(name = "studentdet")
public class StudentTo implements Serializable {
    @Id
    @GeneratedValue
    private Integer sid;
    private String sname;
    private String scity;

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }
   
    public StudentTo(){
       
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getScity() {
        return scity;
    }

    public void setScity(String scity) {
        this.scity = scity;
    }
   
   
   
}

3)StudentToCopy.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.controllers;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author Rishitha
 */
@Entity
@Table(name = "studentdet")
public class StudentTo implements Serializable {
    @Id
    @GeneratedValue
    private Integer sid;
    private String sname;
    private String scity;

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }
   
    public StudentTo(){
       
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getScity() {
        return scity;
    }

    public void setScity(String scity) {
        this.scity = scity;
    }
   
   
   
}


4)StudentDAOI.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.dao;

import org.jl.controllers.StudentTo;
import org.jl.controllers.StudentToCopy;

/**
 *
 * @author Rishitha
 */
public interface StudentDAOI {
   
    public void saveStudentDet(StudentTo st ) throws Exception;
    public void saveStudentDetCopy(StudentToCopy st ) throws Exception;
   
}


5)StudentHibDAO.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.dao;



import org.jl.controllers.StudentTo;
import org.jl.controllers.StudentToCopy;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Rishitha
 */
@Repository
public class StudentHibDAO implements StudentDAOI{
    @Autowired
    private HibernateTemplate ht;
   
    public void saveStudentDet(StudentTo st)  {
        ht.save(st);
       
       
    }

    public void saveStudentDetCopy(StudentToCopy st) throws Exception  {
       ht.save(st);
       if(true)throw new Exception("Intentionally Throwing to test roll back "
               + " both tables.Remove this if you want to store"
               + "in both tables succesfully ");
       
    }

 
   
}


6)

StudentService.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.services;

import org.jl.controllers.StudentTo;
import org.jl.controllers.StudentToCopy;
import org.jl.dao.StudentDAOI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author Rishitha
 */
@Service
public class StudentService {
    @Autowired
    StudentDAOI sdao;
    public void registerStudent(StudentTo st ) throws Exception{
        sdao.saveStudentDet(st);//This tries to save details in to studentdet
        //What I am doing here is just I want
        // to store the student details passed
        // from UI in to two different tables
        //studentdet and studentdetcopy
        //If any problem occurs it has to be rollbacked
        //from both tables
        //I have used hibernatetransactionmanager
        StudentToCopy stss = new StudentToCopy();
        stss.setSname(st.getSname());
        stss.setScity(st.getScity());
        sdao.saveStudentDetCopy(stss);//This tries to save details in to studentdetcopy
       
       
       
    }
    public StudentService(){
       
    }
    public StudentDAOI getSdao() {
        return sdao;
    }

    public void setSdao(StudentDAOI sdao) {
        this.sdao = sdao;
    }
   
   
   
}


7)
dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd" >

     <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="oracle.jdbc.driver.OracleDriver"
        p:url="jdbc:oracle:thin:@localhost:1521:XE"
        p:username="hr" p:password="hr" />
  
     <bean name="ht" class="org.springframework.orm.hibernate3.HibernateTemplate" c:_0-ref="sessionFactory">
     </bean>
  
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/"
          p:suffix=".jsp" />
     <bean id="ptm" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
            c:_0-ref="sessionFactory">
         
     </bean>
    
    
   <bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource">
    <ref bean="ds"/>
  </property>
  <property name="annotatedClasses">
   <list>
    <value>org.jl.controllers.StudentTo</value>
    <value>org.jl.controllers.StudentToCopy</value>
    </list>
  </property>
  <property name="hibernateProperties">
    <props>
    
      <prop key="hibernate.show_sql">true</prop>
      <prop key="hibernate.max_fetch_depth">2</prop>
      <prop key="hibernate.hbm2ddl.auto">update</prop>
    </props>
  </property>
</bean>    
    <context:component-scan base-package="org.jl"/>

</beans>

8)
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

9)
failure.jsp

<%--
    Document   : failure
    Created on : Jan 1, 2014, 8:10:53 PM
    Author     : Rishitha
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Student Registration Failed </h1>
    </body>
</html>

10)
studentReg.jsp

<%--
    Document   : studentReg
    Created on : Jan 1, 2014, 1:07:25 PM
    Author     : Rishitha
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="studentReg.spring" method="post">
           <table>
               <tr>
                   <td>StudentName:</td>
                   <td><input type="text" name="sname"/></td>
               </tr>
               <tr>
                   <td>City</td>
                   <td><input type="text" name="scity"/></td>
               </tr>
               <tr>
                   <td colspan="2"><input type="submit" value="Register"/></td>
               </tr>
           </table>
        </form>
    </body>
</html>

11)
success.jsp

<%--
    Document   : success
    Created on : Jan 1, 2014, 3:45:48 PM
    Author     : Rishitha
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Student Registration Success</h1>
    </body>
</html>

Note:Add Spring libraries,Hibernate Libraries,ojdbc.jar,commons-dbcp.jar,commons-pool.jar,
commons-logging.jar,


No comments:

Post a Comment