Follow Nirav Raval

Thursday 1 August 2013


Spring MVC - Hibernate Demo Application


Hello Friends,

Nice to see you again.
In Previous Sessions  we have seen  Spring MVC with Annotation Demo. And learn how they work.
Today, we will see the example of  Spring MVC with Hibernate basic tutorial.

This demo I have created using Netbeans IDE 7.1.2.
Netbeans provide Spring Project with Hibernate, So no need to find out every Jars as it provides by Netbeans itself.

Ok Here we will create one Student Register Application demo which we previosuly develope without database.

Now we will extend that with adding Hibernate support to persist our data in MySQL Server.

Below is our final output.

Student Registration Demo


For create this application, I have create one Database Table "Student" in MySQL Server as below.
---------------------------------------------------------------------------------------------------------------------------
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(30) DEFAULT NULL,
  `lastname` varchar(30) DEFAULT NULL,
  `telephone` varchar(15) DEFAULT NULL,
  `email` varchar(30) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
---------------------------------------------------------------------------------------------------------------------------

Project Structure


Source Code:
---------------------------------------------------------------------------------------------------------------------------
(1) 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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3-Hibernate</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

---------------------------------------------------------------------------------------------------------------------------
(2) spring-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: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.j2eedeveloper" />

<bean id="jspViewResolver"
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="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />

<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="root" />

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<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>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>

---------------------------------------------------------------------------------------------------------------------------
(3) jdbc.properties
---------------------------------------------------------------------------------------------------------------------------

jdbc.driverClassName= com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

---------------------------------------------------------------------------------------------------------------------------
(4) hibernate.cfg.xml
---------------------------------------------------------------------------------------------------------------------------
<?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.j2eedevloper.model.Student" />
    </session-factory>
   
</hibernate-configuration>

---------------------------------------------------------------------------------------------------------------------------
(5) messages_en.properties
---------------------------------------------------------------------------------------------------------------------------
label.firstname=First Name
label.lastname=Last Name
label.email=Email
label.telephone=Telephone
label.addStudent=Add Student
label.title=Student Manager

label.footer=&copy; niravj2eedeveloper.blogspot.com

---------------------------------------------------------------------------------------------------------------------------
(6) StudentController.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.controller;

import com.j2eedeveloper.service.StudentService;
import com.j2eedevloper.model.Student;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/index")
    public String listContacts(Map<String, Object> map) {

        map.put("student", new Student());
        map.put("studentList", studentService.listStudent());

        return "student";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("student") Student student) {

        studentService.addStudent(student);

        return "redirect:/index";
    }

    @RequestMapping("/delete/{studentId}")
    public String deleteContact(@PathVariable("studentId") Integer studentId) {

        studentService.removeStudent(studentId);

        return "redirect:/index";
    }

}

---------------------------------------------------------------------------------------------------------------------------
(7) StudentDAO.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.dao;

import com.j2eedevloper.model.Student;
import java.util.List;

public interface StudentDAO {

    public void addStudent(Student student);

    public List<Student> listStudent();

    public void removeStudent(Integer id);

}

---------------------------------------------------------------------------------------------------------------------------
(8) StudenttDAOImpl.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.dao;

import com.j2eedevloper.model.Student;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class StudenttDAOImpl implements StudentDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addStudent(Student student) {
        sessionFactory.getCurrentSession().save(student);
    }

    public List<Student> listStudent() {

        return sessionFactory.getCurrentSession().createQuery("from Student").list();
    }

    public void removeStudent(Integer id) {
        Student student = (Student) sessionFactory.getCurrentSession().load(
                Student.class, id);
        if (null != student) {
            sessionFactory.getCurrentSession().delete(student);
        }

    }

}

---------------------------------------------------------------------------------------------------------------------------
(9) StudentService.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.service;

import com.j2eedevloper.model.Student;
import java.util.List;

public interface StudentService {

    public void addStudent(Student student);

    public List<Student> listStudent();

    public void removeStudent(Integer id);

}

---------------------------------------------------------------------------------------------------------------------------
(10) StudentServiceImpl.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedeveloper.service;

import com.j2eedeveloper.dao.StudentDAO;
import com.j2eedevloper.model.Student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDAO studentDAO;

    @Transactional
    public void addStudent(Student student) {
        studentDAO.addStudent(student);
    }

    @Transactional
    public List<Student> listStudent() {

        return studentDAO.listStudent();
    }

    @Transactional
    public void removeStudent(Integer id) {
        studentDAO.removeStudent(id);
    }

}

---------------------------------------------------------------------------------------------------------------------------
(11) Student.java
---------------------------------------------------------------------------------------------------------------------------
package com.j2eedevloper.model;

import javax.persistence.*;

@Entity
@Table(name = "Student")
public class Student {

    @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;

    public String getEmail() {
        return email;
    }

    public String getTelephone() {
        return telephone;
    }

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

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getFirstname() {
        return firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public Integer getId() {
        return id;
    }

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

---------------------------------------------------------------------------------------------------------------------------
(12) student.jsp
---------------------------------------------------------------------------------------------------------------------------

<%@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 MVC Hibernate - Student Manager</title>
        <style type="text/css">
            body {
                font-family: sans-serif;
            }
            .data, .data td {
                border-collapse: collapse;
                width: 100%;
                border: 1px solid #aaa;
                margin: 2px;
                padding: 2px;
            }
            .data th {
                font-weight: bold;
                background-color: #5C82FF;
                color: white;
            }
        </style>
    </head>
    <body>

        <h2><spring:message code="label.title"/></h2>

        <form:form method="post" action="add.html" commandName="student">

            <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.addStudent"/>"/>
                    </td>
                </tr>
            </table>
        </form:form>


        <h3>Students</h3>
        <c:if  test="${!empty studentList}">
            <table class="data">
                <tr>
                    <th style="width: 40%">Name</th>
                    <th style="width: 30%">Email</th>
                    <th style="width: 20%">Telephone</th>
                    <th>&nbsp;</th>
                </tr>
                <c:forEach items="${studentList}" var="student">
                    <tr>
                        <td style="width: 40%">${student.lastname} ${student.firstname} </td>
                        <td style="width: 30%">${student.email}</td>
                        <td style="width: 20%">${student.telephone}</td>
                        <td><a href="delete/${student.id}">delete</a></td>
                    </tr>
                </c:forEach>
            </table>
        </c:if>

        <br/>
        <hr/>
        <h3><spring:message code="label.footer"/></h3>
        <hr/>
    </body>

</html>

---------------------------------------------------------------------------------------------------------------------------
Now run URL http://localhost:8080/SpringHibernate/index  in your browser.
---------------------------------------------------------------------------------------------------------------------------
Hope you find this helpful....!