Wednesday, October 22, 2014

Spring MVC + Hibernate CRUD Web Application


Spring (4) MVC + Hibernate (4) CRUD Web Application

Scope : Develop an web application with using Spring and Hibernate

Objective : Develop a student management application with CRUD functionality.

Requirements : 
  • Eclipe Java EE IDE
  • JDK 1.6
  • MySQL Server 5.5
Step 1 : Create a dynamic web project in eclipse and name it as "SpringSimpleStudentMVC". 

Step 2 : The data base properties defined as below. 

/SpringSimpleStudentMVC/src/database.properties


1
2
3
4
5
6
7
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test
database.user=root
database.password=1234
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect

Step 3 : Create a "Student" domain class under the "com.prem.domain" package.

/SpringSimpleStudentMVC/src/com/prem/domain/Student.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.prem.domain;

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

@Entity
public class Student {
 @Id
 @GeneratedValue
 private int id;

 @Column(name = "FIRSTNAME")
 private String firstName;

 @Column(name = "LASTNAME")
 private String lastName;

 @Column(name = "EMAIL")
 private String email;

 @Column(name = "CONTACTNO")
 private String phone;

 public int getId() {
  return id;
 }

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

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

}


Step 4 : Create "StudentDAO" and "StudentDAOImpl" interface and class file under the "com.prem.dao" package.

/SpringSimpleStudentMVC/src/com/prem/dao/StudentDAO.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.prem.dao;

import java.util.List;
import com.prem.domain.Student;

public interface StudentDAO {

 public void saveStudent(Student student);

 public List<Student> getAllStudent();

 public Student getStudentById(int id);

 public void updateStudent(Student student);

 public void deleteStudent(int id);
}

The "StudentDAOImpl" class looks like as below.

/SpringSimpleStudentMVC/src/com/prem/dao/StudentDAOImpl.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.prem.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.prem.domain.Student;

public class StudentDAOImpl implements StudentDAO {

 @Autowired
 private SessionFactory sessionFactory;

 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 @Transactional
 public void saveStudent(Student student) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(student);
  tx.commit();
  Serializable id = session.getIdentifier(student);
  session.close();
 }

 @Override
 public List<Student> getAllStudent() {
  Session session = sessionFactory.openSession();
  List<Student> studentList = session.createQuery("from Student").list();
  session.close();
  return studentList;
 }

 @Override
 public Student getStudentById(int id) {
  Session session = sessionFactory.openSession();
  return (Student) session.load(Student.class, new Integer(id));
 }

 @Override
 public void updateStudent(Student student) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(student);
  tx.commit();
  Serializable id = session.getIdentifier(student);
  session.close();

 }

 @Override
 @Transactional
 public void deleteStudent(int id) {
  Session session = sessionFactory.openSession();  
    Transaction tx = session.beginTransaction();  
    Student student = (Student) session.load(Student.class, id);  
    session.delete(student);  
    tx.commit();  
    Serializable ids = session.getIdentifier(student);  
    session.close();  
 }

}

Step 5: Now the time to create a "StudentService" interface and the "StudentServiceManger" class under the "com.prem.service" package.

/SpringSimpleStudentMVC/src/com/prem/service/StudentService.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package com.prem.service;

import java.util.List;
import com.prem.domain.Student;

public interface StudentService {
 public void saveStudentDetails(Student student);

 public List<Student> getAllStudents();

 public Student getStudentDeatilsById(int id);

 public void updateStudentDeatils(Student student);

 public void deleteStudentDetails(int id);
}

And the StudentServiceManger class as below.

/SpringSimpleStudentMVC/src/com/prem/service/StudentServiceManager.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.prem.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.prem.dao.StudentDAO;
import com.prem.domain.Student;
import com.prem.service.StudentService;

@Service
public class StudentServiceManager implements StudentService {
 
 @Autowired
 private StudentDAO studentDAO;

 public StudentDAO getStudentDAO() {
  return studentDAO;
 }

 public void setStudentDAO(StudentDAO studentDAO) {
  this.studentDAO = studentDAO;
 }

 @Override
 @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
 public void saveStudentDetails(Student student) {
  studentDAO.saveStudent(student);
 }

 @Override
 public List<Student> getAllStudents() {
  return studentDAO.getAllStudent();
 }

 @Override
 public Student getStudentDeatilsById(int id) {
  return studentDAO.getStudentById(id);
 }

 @Override
 public void updateStudentDeatils(Student student) {
  studentDAO.updateStudent(student);
 }

 @Override
 public void deleteStudentDetails(int id) {
  studentDAO.deleteStudent(id);
 }

}


Step 6 : Now we are going to create the "StudentController" class under the package "com.prem.controller".


/SpringSimpleStudentMVC/src/com/prem/controller/StudentController.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.prem.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.prem.domain.Student;
import com.prem.service.StudentService;

@Controller
public class StudentController {

 @Autowired
 @Qualifier(value="studentService")
 StudentService studentService;

 public StudentService getStudentService() {
  return studentService;
 }

 public void setStudentService(StudentService studentService) {
  this.studentService = studentService;
 }

 @RequestMapping("form")
 public ModelAndView getForm(@ModelAttribute Student student) {
  return new ModelAndView("form");
 }

 @RequestMapping("register")
 @Transactional(readOnly=false)
 public ModelAndView registerUser(@ModelAttribute Student student) {
  studentService.saveStudentDetails(student);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("list")
 public ModelAndView getList() {
  List<Student> studentList = studentService.getAllStudents();
  return new ModelAndView("list", "studentList", studentList);
 }

 @RequestMapping("delete")
 public ModelAndView deleteUser(@RequestParam int id) {
  studentService.deleteStudentDetails(id);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("edit")
 public ModelAndView editUser(@RequestParam int id,
   @ModelAttribute Student student) {
  Student studentObject = studentService.getStudentDeatilsById(id);
  return new ModelAndView("edit", "studentObject", studentObject);
 }

 @RequestMapping("update")
 public ModelAndView updateUser(@ModelAttribute Student student) {
  studentService.updateStudentDeatils(student);
  return new ModelAndView("redirect:list");
 }

}


Step 7 : The spring configurations looks as below.

/SpringSimpleStudentMVC/WebContent/WEB-INF/mvc-dispatcher.xml


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<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:property-placeholder location="classpath:database.properties" />
 <context:component-scan base-package="com.prem.dao.impl" />
 <context:component-scan base-package="com.prem.service.manager" />
 <context:component-scan base-package="com.prem.controller" />

 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="persistenceExceptionTranslationPostProcessor"
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

 <bean
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="database.properties" />
 </bean>

 <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
  id="dataSource">
  <property name="driverClassName" value="${database.driver}"></property>
  <property name="url" value="${database.url}"></property>
  <property name="username" value="${database.user}"></property>
  <property name="password" value="${database.password}"></property>
 </bean>

 <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
  id="sessionFactory">
  <property name="dataSource" ref="dataSource"></property>
  <property name="annotatedClasses"> 
   <list> 
    <value>com.prem.domain.Student</value> 
   </list> 
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>
   </props>
  </property>
 </bean>
 
 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
 
 <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager"
  id="hibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>

 <bean id="studentDAO" class="com.prem.dao.StudentDAOImpl">
 </bean> 
 <bean id="studentService" class="com.prem.service.StudentServiceManager">
 </bean> 
</beans>


Step 8 : Now the time to create the jsp files for student registration.

/SpringSimpleStudentMVC/WebContent/WEB-INF/pages/form.jsp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Student Registration Form</title>  
</head>  
<body >  
 <center>  
  
  <div style="color: blue; font-size: 25px">Student  Registration Form</div>  
 
  <c:url var="userRegistration" value="saveUser.html" />  
  <form:form id="registerForm" modelAttribute="student" method="post" action="register">  
   <table width="500px" height="170px">  
    <tr>  
     <td><form:label path="firstName">First Name</form:label>  
     </td>  
     <td><form:input path="firstName" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="lastName">Last Name</form:label>  
     </td>  
     <td><form:input path="lastName" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="email">Email</form:label>  
     </td>  
     <td><form:input path="email" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="phone">Phone</form:label>  
     </td>  
     <td><form:input path="phone" />  
     </td>  
    </tr>  
    <tr>  
     <td></td>  
     <td><input type="submit" value="Register" /></td>  
    </tr>  
   </table>  
  </form:form>  
  
  <a href="list">View All Students List</a>  
 </center>  
</body>  
</html>  

Step 9 : Now the time to run and see the behavior of the application.

The student registration screen looks like as below.





And the student details screen looks like as below.




No comments:

Post a Comment