Affiliate Marketing
Pls Subscribe this channel Subscribe ® Registered teknosys.in
mvn archetype:generate -DgroupId=com.howtodoinjava.app -DartifactId=Spring3HibernateIntegration -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=falseNow, convert this web application to ecplise dynamic web project using below commands.
cd Spring3HibernateIntegration mvn eclipse:eclipse -Dwtpversion=2.0Step 2) Update pom.xml file to include spring 3 and hibernate dependencies. It will also include mysql driver added in project references. Now again execute command “mvn eclipse:eclipse -Dwtpversion=2.0” to reflect the dependencies in project.
CREATE TABLE EMPLOYEE
(
ID INT PRIMARY KEY AUTO_INCREMENT,
FIRSTNAME VARCHAR(30),
LASTNAME VARCHAR(30),
TELEPHONE VARCHAR(15),
EMAIL VARCHAR(30),
CREATED TIMESTAMP DEFAULT NOW()
);
Step 4) Now its time to write EmployeeEntity.java. This class will be mapped to Employee table in database using hibernate. JPA will include any class annotated with @Entity in the persistence management setup. You don’t need persistence.xml if you use annotations.package com.howtodoinjava.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="EMPLOYEE")
public class EmployeeEntity
{
@Id
@Column(name="ID")
@GeneratedValue
private Integer id;
@Column(name="FIRSTNAME")
private String firstname;
@Column(name="LASTNAME")
private String lastname;
@Column(name="EMAIL")
private String email;
@Column(name="TELEPHONE")
private String telephone;
//Add setters and getters
}
Step 5) Lets write our DAO classes which will be responsible for database interaction. This class will be essentially using the hibernate session factory for database interaction. The session factory implementation will be injected into reference variable at runtime using spring IoC feature.package com.howtodoinjava.dao;
import java.util.List;
import com.howtodoinjava.entity.EmployeeEntity;
public interface EmployeeDAO
{
public void addEmployee(EmployeeEntity employee);
public List<EmployeeEntity> getAllEmployees();
public void deleteEmployee(Integer employeeId);
}
EmployeeDaoImpl.javapackage com.howtodoinjava.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.howtodoinjava.entity.EmployeeEntity;
@Repository
public class EmployeeDaoImpl implements EmployeeDAO
{
@Autowired
private SessionFactory sessionFactory;
@Override
public void addEmployee(EmployeeEntity employee) {
this.sessionFactory.getCurrentSession().save(employee);
}
@SuppressWarnings("unchecked")
@Override
public List<EmployeeEntity> getAllEmployees() {
return this.sessionFactory.getCurrentSession().createQuery("from EmployeeEntity").list();
}
@Override
public void deleteEmployee(Integer employeeId) {
EmployeeEntity employee = (EmployeeEntity) sessionFactory.getCurrentSession().load(
EmployeeEntity.class, employeeId);
if (null != employee) {
this.sessionFactory.getCurrentSession().delete(employee);
}
}
}
Step 5) I have written a manager layer also which seems redundant in this demo due less complexity but it as always considered best practice if you write this. This layer will simply take call from controller and pass this call to dao layer.package com.howtodoinjava.service;
import java.util.List;
import com.howtodoinjava.entity.EmployeeEntity;
public interface EmployeeManager {
public void addEmployee(EmployeeEntity employee);
public List<EmployeeEntity> getAllEmployees();
public void deleteEmployee(Integer employeeId);
}
EmployeeManagerImpl.javapackage com.howtodoinjava.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.howtodoinjava.dao.EmployeeDAO;
import com.howtodoinjava.entity.EmployeeEntity;
@Service
public class EmployeeManagerImpl implements EmployeeManager
{
@Autowired
private EmployeeDAO employeeDAO;
@Override
@Transactional
public void addEmployee(EmployeeEntity employee) {
employeeDAO.addEmployee(employee);
}
@Override
@Transactional
public List<EmployeeEntity> getAllEmployees() {
return employeeDAO.getAllEmployees();
}
@Override
@Transactional
public void deleteEmployee(Integer employeeId) {
employeeDAO.deleteEmployee(employeeId);
}
public void setEmployeeDAO(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
}
Step 6) Now its time to write the controller which will actually be called from spring framework’s dispatcher servlet to process actual application logic.package com.howtodoinjava.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.howtodoinjava.entity.EmployeeEntity;
import com.howtodoinjava.service.EmployeeManager;
@Controller
public class EditEmployeeController
{
@Autowired
private EmployeeManager employeeManager;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String listEmployees(ModelMap map)
{
map.addAttribute("employee", new EmployeeEntity());
map.addAttribute("employeeList", employeeManager.getAllEmployees());
return "editEmployeeList";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addEmployee(@ModelAttribute(value="employee") EmployeeEntity employee, BindingResult result)
{
employeeManager.addEmployee(employee);
return "redirect:/";
}
@RequestMapping("/delete/{employeeId}")
public String deleteEmplyee(@PathVariable("employeeId") Integer employeeId)
{
employeeManager.deleteEmployee(employeeId);
return "redirect:/";
}
public void setEmployeeManager(EmployeeManager employeeManager) {
this.employeeManager = employeeManager;
}
}
Step 7) Now we will write our application’s view layer which is actually a .jsp file.<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Spring 3 hibernate integration example on www.howtodoinjava.com</title>
</head>
<body>
<h2>Employee Management Screen : Spring 3 hibernate integration example on www.howtodoinjava.com</h2>
<form:form method="post" action="add" commandName="employee">
<table>
<tr>
<td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="email"><spring:message code="label.email"/></form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="<spring:message code="label.add"/>"/>
</td>
</tr>
</table>
</form:form>
<h3>Employees</h3>
<c:if test="${!empty employeeList}">
<table class="data">
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Action</th>
</tr>
<c:forEach items="${employeeList}" var="emp">
<tr>
<td>${emp.lastname}, ${emp.firstname} </td>
<td>${emp.email}</td>
<td>${emp.telephone}</td>
<td>delete</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
Step 8) Our java code is complete and now its time to configure the application. Lets start from web.xml. In web.xml, we will configure the front controller for spring framework that is DispatcherServlet.<?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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>employee</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>employee</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/employee-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Step 9) Lets configure spring framework for hibernate data source, message resources, view resolvers and other such things.<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="com.howtodoinjava.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties"></bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}"></bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl"></bean>
<bean id="employeeManager" class="com.howtodoinjava.service.EmployeeManagerImpl"></bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
Step 10) Hibernate configuration becomes simple when using annotation. Lets see how easy it is.<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="com.howtodoinjava.entity.EmployeeEntity"></mapping>
</session-factory>
</hibernate-configuration>
Step 11) Lets mention jdbc connection properties and message resource properties.jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.dialect=org.hibernate.dialect.MySQLDialect jdbc.databaseurl=jdbc:mysql://127.0.0.1:3306/test jdbc.username=root jdbc.password=passwordmessages_en.properties
label.firstname=First Name label.lastname=Last Name label.email=Email label.telephone=Telephone label.add=Add Employee label.menu=Actions label.title=Employee Form label.footer=www.HowToDoInJava.comThat’s it. Your application is ready to be deployed on server of your choice. At the end, your project structure should look like this.
Comments