Posted In: Spring + Hibernate Integration

Spring3 + Hibernate3 example

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
  xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <display-name>SpringApp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <context-param>
    <description>spring context configuration</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/springapp-servlet.xml</param-value>
  </context-param>
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>springapp</param-value>
  </context-param>

  <context-param>
    <description>
      log4j configuration used by Log4jConfigListener
    </description>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/classes/log4j.xml</param-value>
  </context-param>
  <context-param>
    <description>
      log4j configuration used by Log4jConfigListener
    </description>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>1000</param-value>
  </context-param>
  <listener>
    <!-- Bootstrap listener for custom log4j initialization in a web environment -->
    <listener-class>
      org.springframework.web.util.Log4jConfigListener
    </listener-class>
  </listener>

  <listener>
    <!-- Bootstrap listener to start up Spring's root WebApplicationContext. -->
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

  <servlet>
    <display-name>springapp</display-name>
    <servlet-name>springapp</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/employee/list</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/employee/delete</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/employee/insert</url-pattern>
  </servlet-mapping>
    <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/employee/update</url-pattern>
  </servlet-mapping>
</web-app>
<?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:context="http://www.springframework.org/schema/context"
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">
  
  <context:component-scan base-package="com.company.springapp"/>
  
  <bean id="messages"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="message" />
  </bean>
  <alias name="messages" alias="messageSource" />

  <bean id="view-resolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
      value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  </bean>
  
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
      <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
      <property name="url" value="jdbc:hsqldb:hsql://localhost:9001/trupti_db"/>
      <property name="username" value="sa"/>
      <property name="password" value=""/>
  </bean>
  
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
      <list>
        <value>employee.hbm.xml</value>
      </list>
    </property>		
    <property name="hibernateProperties">
      <props> 
        <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> 
        <prop key="current_session_context_class">thread</prop> 
        <prop key="hibernate.show_sql">true</prop> 
      </props> 		
    </property>	 
  </bean>  

  <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">	
    <property name="sessionFactory" ref="sessionFactory" /> 
  </bean>	
	
  <bean id="myService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager" ref="txManager"/>
    <property name="target" ref="employeeDao"/>			
    <property name="transactionAttributes">
    <props>
      <prop key="list">PROPAGATION_REQUIRED,readOnly</prop>
      <prop key="insert">PROPAGATION_REQUIRED</prop>
      <prop key="update">PROPAGATION_REQUIRED</prop>
      <prop key="delete">PROPAGATION_REQUIRED</prop>
    </props>
    </property>
  </bean>
	
  <bean id="employeeDao"
    class="com.company.springapp.EmployeeDao">
	<property name="sessionFactory" ref="sessionFactory"></property>
  </bean>

  <bean id="employeeController"
    class="com.company.springapp.EmployeeController">
	<property name="employeeDao" ref="employeeDao"></property>
  </bean>
</beans>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.company.springapp">
    <class name="Employee" table="EMPLOYEE_DTL">
        <id name="empId" column="EMP_ID">
			<generator class="sequence">
			    <param name="sequence">employee_seq</param>
			</generator>
		</id>
        <property name="firstName" type="string" column="FIRST_NM"/>
        <property name="lastName" type="string" column="LAST_NM"/>
        <property name="dateofBirth" type="date" column="DT_OF_BIRTH"/>
        <property name="hireDate" type="date" column="HIRE_DATE"/>
    </class>
</hibernate-mapping>
package com.company.springapp;

import java.io.Serializable;
import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

public class Employee implements Serializable
{
  private Long empId;
  private String firstName;
  private String lastName;
  private Date dateofBirth;
  private Date hireDate;
  public Date getDateofBirth() {
    return dateofBirth;
  }
  public void setDateofBirth(Date dateofBirth) {
    this.dateofBirth = dateofBirth;
  }
  public Long getEmpId() {
    return empId;
  }
  public void setEmpId(Long empId) {
    this.empId = empId;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public Date getHireDate() {
    return hireDate;
  }
  public void setHireDate(Date hireDate) {
    this.hireDate = hireDate;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
}
package com.company.springapp;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value="/employee")
public class EmployeeController
{
  private static final Logger logger = Logger.getLogger(EmployeeController.class);
  private EmployeeDao employeeDao;
  
  public void setEmployeeDao(EmployeeDao employeeDao) {
	this.employeeDao = employeeDao;
  }

  @InitBinder
  public void initBinder(WebDataBinder binder) 
  {
    logger.info("start");
	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	dateFormat.setLenient(false);
	binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
  }
  
  @RequestMapping(value="/list")
  protected ModelAndView list(@ModelAttribute("command") Employee command)
      throws Exception 
  {	
	logger.info("start");
	ModelAndView mav = new ModelAndView();
    try
    {
    	mav.setViewName("employee_maintenance");
    	List employeeList = employeeDao.list();
    	mav.addObject("employeeList", employeeList);
    }
    catch (Exception e)
    {
        logger.error(e,e);
    }
    return mav;
  }

  @RequestMapping(value="/delete")
  protected ModelAndView delete(@ModelAttribute("command") Employee command)
      throws Exception 
  {	
	logger.info("start::"+ BeanUtils.describe(command));
	ModelAndView mav = new ModelAndView();
    try
    { 
    	mav.setViewName("employee_maintenance");
    	employeeDao.delete(command);
    	List employeeList = employeeDao.list();
    	mav.addObject("employeeList", employeeList);
    }
    catch (Exception e)
    {
        logger.error(e,e);
    }
    return mav;
  }

  @RequestMapping(value="/insert")
  protected ModelAndView insert(@ModelAttribute("command") Employee command)
      throws Exception 
  {	
	logger.info("start::"+ BeanUtils.describe(command));
	ModelAndView mav = new ModelAndView();
    try
    { 
    	mav.setViewName("employee_maintenance");
    	employeeDao.insert(command);
    	List employeeList = employeeDao.list();
    	mav.addObject("employeeList", employeeList);
    }
    catch (Exception e)
    {
        logger.error(e,e);
    }
    return mav;
  }

  @RequestMapping(value="/update")
  protected ModelAndView update(@ModelAttribute("command") Employee command)
      throws Exception 
  {	
	logger.info("start::"+ BeanUtils.describe(command));
	ModelAndView mav = new ModelAndView();
    try
    { 
    	mav.setViewName("employee_maintenance");
    	employeeDao.update(command);
    	List employeeList = employeeDao.list();
    	mav.addObject("employeeList", employeeList);
    }
    catch (Exception e)
    {
      logger.error(e,e);
    }
    return mav;
  }
}
package com.company.springapp;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class EmployeeDao
{
	private HibernateTemplate hbrnTmplt;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hbrnTmplt = new HibernateTemplate(sessionFactory);
	}
	
	public List list() {
		List list = hbrnTmplt.find("from Employee");
		return list;
	}	

	public void insert(Employee newEmployee) {
		hbrnTmplt.save(newEmployee);
	}	

	public void update(Employee employee) {
		hbrnTmplt.update(employee);
	}	

	public void delete(Employee employee) {
		hbrnTmplt.delete(employee);
	}	
}
<%@ page import="com.company.springapp.Employee"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<jsp:useBean id="employeeList" class="java.util.ArrayList"
  scope="request" />
<html>
<head>
<script>
function submitForm(insUpdDel,rownum)
{
	if(insUpdDel == 'insert')
	{
		document.frm.firstName.value =  document.getElementById('firstNameIsrt').value;	
		document.frm.lastName.value =  document.getElementById('lastNameIsrt').value;	
		document.frm.dateofBirth.value =  document.getElementById('dateofBirthIsrt').value;	
		document.frm.hireDate.value =  document.getElementById('hireDateIsrt').value;	
	}
	else if(insUpdDel == 'delete')
	{
		document.frm.empId.value =  document.getElementById('empId'+rownum).value;	
	}
	else if(insUpdDel == 'update')
	{
		document.frm.empId.value =  document.getElementById('empId'+rownum).value;
		document.frm.firstName.value =  document.getElementById('firstName'+rownum).value;	
		document.frm.lastName.value =  document.getElementById('lastName'+rownum).value;	
		document.frm.dateofBirth.value =  document.getElementById('dateofBirth'+rownum).value;	
		document.frm.hireDate.value =  document.getElementById('hireDate'+rownum).value;	
	}
	document.frm.action = "<%=request.getContextPath()%>/employee/"+insUpdDel;
	document.frm.method = "post";
	document.frm.submit();
}
</script>
</head>
<body>
<form name='frm' >
<table bgcolor="#EFEFEF" border="1">
  <tr>
    <td><Strong>Employee Id</Strong></td>
    <td><Strong>First Name</Strong></td>
    <td><Strong>Last Name</Strong></td>
    <td><Strong>Date of Birth</Strong></td>
    <td><Strong>Hire Date</Strong></td>
    <td><Strong>&nbsp;</Strong></td>
    <td><Strong>&nbsp;</Strong></td>
  </tr>
  <c:forEach var="employee" items="${employeeList}" varStatus="counter">
    <tr>
      <td><input type='text' name='empId${counter.index}'
        value='${employee.empId}' size='20' readonly /></td>
      <td><input type='text' name='firstName${counter.index}'
        value='${employee.firstName}' size='20' /></td>
      <td><input type='text' name='lastName${counter.index}'
        value='${employee.lastName}' size='20' /></td>
      <td><input type='text' name='dateofBirth${counter.index}'
        value='${employee.dateofBirth}' size='20' /></td>
      <td><input type='text' name='hireDate${counter.index}'
        value='${employee.hireDate}' size='20' /></td>
      <td><input type='button' value='Delete'  onclick="submitForm('delete',${counter.index})" /></td>
      <td><input type='button' value='Update'  onclick="submitForm('update',${counter.index})" /></td>
    </tr>
  </c:forEach>
  <tr>
    <td>&nbsp;</td>
    <td><input type='text' name='firstNameIsrt' size='20' /></td>
    <td><input type='text' name='lastNameIsrt' size='20' /></td>
    <td><input type='text' name='dateofBirthIsrt' size='20' /></td>
    <td><input type='text' name='hireDateIsrt' size='20' /></td>
    <td><input type='button' value='Insert' onclick="submitForm('insert')" /></td>
    <td>&nbsp;</td>
  </tr>
</table>
<input type='hidden' name='empId'/>
<input type='hidden' name='firstName'/>
<input type='hidden' name='lastName'/>
<input type='hidden' name='dateofBirth'/>
<input type='hidden' name='hireDate'/>
</form>
</body>
</html>

Tags: ,

by , on January 14th, 2017

  • Categories