Spring MVC with Hibernate CRUD example

In this article, We will learn about how to integrate Hibernate with Spring MVC application

Step 1

Create Spring MVC project, Please refer Spring MVC setup in eclipse article on how to do it.

Project structure


springmvc_hibernate_crud_proj_structure

Step 2

Update pom.xml with required dependencies

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
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SpringMVCHibernateCRUD</groupId>
    <artifactId>SpringMVCHibernateCRUD</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringMVCHibernateCRUD Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.6.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SpringMVCHibernateCRUD</finalName>
    </build>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>SpringMVCHibernateCRUD</groupId>
	<artifactId>SpringMVCHibernateCRUD</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVCHibernateCRUD Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringMVCHibernateCRUD</finalName>
	</build>
</project>

Step 3

Update web.xml file with Dispatcher servlet

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
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <!-- Spring MVC dispatcher servlet -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
            /WEB-INF/spring-mvc.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-mvc.xml
        </param-value>
    </context-param>
</web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <!-- Spring MVC dispatcher servlet -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
            /WEB-INF/spring-mvc.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-mvc.xml
        </param-value>
    </context-param>
</web-app>


we have defined a dispatcher servlet in web.xml and mapped it by the URL pattern “/”

Step 4

Create the Employee class

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
package com.kb.model;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name="Employee")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "Employee_Id")
    private Integer employeeId;
    
    @Column(name = "FirstName")
    private String firstName;
    
    @Column(name = "LastName")
    private String lastName;
    
    @Column(name = "Age")
    private Integer age;
    
    @Column(name = "Education")
    private String education;
    
    @Column(name = "Salary")
    private Double salary;
    
    public Integer getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(Integer employeeId) {
        this.employeeId = employeeId;
    }
    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 Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getEducation() {
        return education;
    }
    public void setEducation(String education) {
        this.education = education;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
}
package com.kb.model;

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

@Entity
@Table(name="Employee")
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Employee_Id")
	private Integer employeeId;
	
	@Column(name = "FirstName")
	private String firstName;
	
	@Column(name = "LastName")
	private String lastName;
	
	@Column(name = "Age")
	private Integer age;
	
	@Column(name = "Education")
	private String education;
	
	@Column(name = "Salary")
	private Double salary;
	
	public Integer getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(Integer employeeId) {
		this.employeeId = employeeId;
	}
	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 Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
}

Step 5

Create the controller class

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
package com.kb.controllers;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 com.kb.model.Employee;
import com.kb.service.EmployeeService;
 
@Controller
public class EmployeeController {
    
    @Autowired
    private EmployeeService employeeService;
 
    @RequestMapping(value = "/employees", method = RequestMethod.GET)
    public String listemployees(Model model) {
        model.addAttribute("employee", new Employee());
        model.addAttribute("employeeList", employeeService.listEmployees());
        return "employee";
    }
 
    // Same method For both Add and Update Employee
    @RequestMapping(value = "/employee/add", method = RequestMethod.POST)
    public String addemployee(@ModelAttribute("employee") Employee employee) {
 
        if (employee.getEmployeeId()==null || employee.getEmployeeId() == 0) {
            // new employee, add it
            employeeService.addEmployee(employee);
        } else {
            // existing employee, call update
            employeeService.updateEmployee(employee);
        }
 
        return "redirect:/employees";
 
    }
 
    @RequestMapping("/employee/remove/{id}")
    public String removeemployee(@PathVariable("id") int id) {
 
        employeeService.removeEmployee(id);
        return "redirect:/employees";
    }
 
    @RequestMapping("/employee/edit/{id}")
    public String editemployee(@PathVariable("id") int id, Model model) {
        model.addAttribute("employee", employeeService.getEmployeeById(id));
        model.addAttribute("employeeList", employeeService.listEmployees());
        return "employee";
    }
}
package com.kb.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 com.kb.model.Employee;
import com.kb.service.EmployeeService;

@Controller
public class EmployeeController {
	
	@Autowired
	private EmployeeService employeeService;

	@RequestMapping(value = "/employees", method = RequestMethod.GET)
	public String listemployees(Model model) {
		model.addAttribute("employee", new Employee());
		model.addAttribute("employeeList", employeeService.listEmployees());
		return "employee";
	}

	// Same method For both Add and Update Employee
	@RequestMapping(value = "/employee/add", method = RequestMethod.POST)
	public String addemployee(@ModelAttribute("employee") Employee employee) {

		if (employee.getEmployeeId()==null || employee.getEmployeeId() == 0) {
			// new employee, add it
			employeeService.addEmployee(employee);
		} else {
			// existing employee, call update
			employeeService.updateEmployee(employee);
		}

		return "redirect:/employees";

	}

	@RequestMapping("/employee/remove/{id}")
	public String removeemployee(@PathVariable("id") int id) {

		employeeService.removeEmployee(id);
		return "redirect:/employees";
	}

	@RequestMapping("/employee/edit/{id}")
	public String editemployee(@PathVariable("id") int id, Model model) {
		model.addAttribute("employee", employeeService.getEmployeeById(id));
		model.addAttribute("employeeList", employeeService.listEmployees());
		return "employee";
	}
}

Step 6

Create the EmployeeService interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.kb.service;
 
import java.util.List;
 
import com.kb.model.Employee;
 
public interface EmployeeService {
    
    public void addEmployee(Employee employee);
    
    public void updateEmployee(Employee employee);
    
    public Employee getEmployeeById(int id);
    
    public void removeEmployee(int id);
    
    public List<Employee> listEmployees();
 
 
}
package com.kb.service;

import java.util.List;

import com.kb.model.Employee;

public interface EmployeeService {
	
	public void addEmployee(Employee employee);
	
	public void updateEmployee(Employee employee);
	
	public Employee getEmployeeById(int id);
	
	public void removeEmployee(int id);
	
	public List<Employee> listEmployees();


}

Step 7

Create the EmployeeServiceImpl class

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
package com.kb.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.kb.dao.EmployeeDAO;
 
import com.kb.model.Employee;
 
@Service
public class EmployeeServiceImpl implements EmployeeService {
    
    @Autowired
    private EmployeeDAO employeeDAO;
 
    public void setemployeeDAO(EmployeeDAO employeeDAO) {
        this.employeeDAO = employeeDAO;
    }
 
    @Override
    @Transactional
    public void addEmployee(Employee employee) {
        employeeDAO.addEmployee(employee);
    }
 
    @Override
    @Transactional
    public void updateEmployee(Employee employee) {
        employeeDAO.updateEmployee(employee);
    }
 
    @Override
    @Transactional
    public List<Employee> listEmployees() {
        return this.employeeDAO.listEmployees();
    }
 
    @Override
    @Transactional
    public Employee getEmployeeById(int id) {
        return employeeDAO.getEmployeeById(id);
    }
 
    @Override
    @Transactional
    public void removeEmployee(int id) {
        employeeDAO.removeEmployee(id);
    }
}
package com.kb.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.kb.dao.EmployeeDAO;

import com.kb.model.Employee;

@Service
public class EmployeeServiceImpl implements EmployeeService {
	
	@Autowired
	private EmployeeDAO employeeDAO;

	public void setemployeeDAO(EmployeeDAO employeeDAO) {
		this.employeeDAO = employeeDAO;
	}

	@Override
	@Transactional
	public void addEmployee(Employee employee) {
		employeeDAO.addEmployee(employee);
	}

	@Override
	@Transactional
	public void updateEmployee(Employee employee) {
		employeeDAO.updateEmployee(employee);
	}

	@Override
	@Transactional
	public List<Employee> listEmployees() {
		return this.employeeDAO.listEmployees();
	}

	@Override
	@Transactional
	public Employee getEmployeeById(int id) {
		return employeeDAO.getEmployeeById(id);
	}

	@Override
	@Transactional
	public void removeEmployee(int id) {
		employeeDAO.removeEmployee(id);
	}
}

Step 8

Create the EmployeeDAO interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.kb.dao;
 
import java.util.List;
 
import com.kb.model.Employee;
 
public interface EmployeeDAO {
    
    public void addEmployee(Employee employee);
    
    public void updateEmployee(Employee employee);
    
    public Employee getEmployeeById(int id);
    
    public void removeEmployee(int id);
    
    public List<Employee> listEmployees();
 
}
package com.kb.dao;

import java.util.List;

import com.kb.model.Employee;

public interface EmployeeDAO {
	
	public void addEmployee(Employee employee);
	
	public void updateEmployee(Employee employee);
	
	public Employee getEmployeeById(int id);
	
	public void removeEmployee(int id);
	
	public List<Employee> listEmployees();

}

Step 9

Create the EmployeeDAOImpl class

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.kb.dao;
 
import java.util.List;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import com.kb.model.Employee;
 
@Repository
public class EmployeeDAOImpl implements EmployeeDAO{
    
    @Autowired
     private SessionFactory sessionFactory;
    
    @Override
    public void addEmployee(Employee employee) {
        Session session = sessionFactory.getCurrentSession();
        session.persist(employee);
    }
 
    @Override
    public void updateEmployee(Employee employee) {
        Session session = sessionFactory.getCurrentSession();
        session.update(employee);
    }
 
    @SuppressWarnings("unchecked")
    @Override
    public List<Employee> listEmployees() {
        Session session = sessionFactory.getCurrentSession();
        List<Employee> EmployeesList = session.createQuery("from Employee").list();
        return EmployeesList;
    }
 
    @Override
    public Employee getEmployeeById(int id) {
        Session session = sessionFactory.getCurrentSession();       
        Employee employee = (Employee) session.get(Employee.class, new Integer(id));
        return employee;
    }
 
    @Override
    public void removeEmployee(int id) {
        Session session = sessionFactory.getCurrentSession();
        Employee employee = (Employee) session.get(Employee.class, new Integer(id));
        if(null != employee){
            session.delete(employee);
        }
    }
}
package com.kb.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kb.model.Employee;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO{
	
	@Autowired
	 private SessionFactory sessionFactory;
	
	@Override
	public void addEmployee(Employee employee) {
		Session session = sessionFactory.getCurrentSession();
		session.persist(employee);
	}

	@Override
	public void updateEmployee(Employee employee) {
		Session session = sessionFactory.getCurrentSession();
		session.update(employee);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> listEmployees() {
		Session session = sessionFactory.getCurrentSession();
		List<Employee> EmployeesList = session.createQuery("from Employee").list();
		return EmployeesList;
	}

	@Override
	public Employee getEmployeeById(int id) {
		Session session = sessionFactory.getCurrentSession();		
		Employee employee = (Employee) session.get(Employee.class, new Integer(id));
		return employee;
	}

	@Override
	public void removeEmployee(int id) {
		Session session = sessionFactory.getCurrentSession();
		Employee employee = (Employee) session.get(Employee.class, new Integer(id));
		if(null != employee){
			session.delete(employee);
		}
	}
}

Step 10

Create the Spring configuration file

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
<?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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.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-4.0.xsd">
 
    <context:component-scan base-package="com.kb" />
    <mvc:annotation-driven />
    <context:property-placeholder location="classpath:database.properties"/>
 
        <tx:annotation-driven transaction-manager="hibernateTransactionManager" />
 
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/" />
            <property name="suffix" value=".jsp" />
        </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.hibernate5.LocalSessionFactoryBean"
            id="sessionFactory">
            <property name="dataSource" ref="dataSource"></property>
            <property name="annotatedClasses">
                <list>
                    <value>com.kb.model.Employee</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>
 
        <bean class="org.springframework.orm.hibernate5.HibernateTransactionManager"
            id="hibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </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="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="en" />
    </bean>
 
    <mvc:interceptors>
        <bean id="localeChangeInterceptor"
            class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="language" />
        </bean>
    </mvc:interceptors>
 
</beans>
<?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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.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-4.0.xsd">

	<context:component-scan base-package="com.kb" />
	<mvc:annotation-driven />
	<context:property-placeholder location="classpath:database.properties"/>

		<tx:annotation-driven transaction-manager="hibernateTransactionManager" />

		<bean id="viewResolver"
			class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/WEB-INF/pages/" />
			<property name="suffix" value=".jsp" />
		</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.hibernate5.LocalSessionFactoryBean"
			id="sessionFactory">
			<property name="dataSource" ref="dataSource"></property>
			<property name="annotatedClasses">
				<list>
					<value>com.kb.model.Employee</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>

		<bean class="org.springframework.orm.hibernate5.HibernateTransactionManager"
			id="hibernateTransactionManager">
			<property name="sessionFactory" ref="sessionFactory"></property>
		</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="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="en" />
    </bean>
 
    <mvc:interceptors>
        <bean id="localeChangeInterceptor"
            class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="language" />
        </bean>
    </mvc:interceptors>

</beans>

Step 11

Create database.properties

database.driver=com.mysql.jdbc.Driver

database.url=jdbc:mysql://localhost:3306/javainsimpleway

database.user=root

database.password=root

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

hibernate.hbm2ddl.auto=update

Step 12

Create messages_en.properties

AddEmployee=Add New Employee

EmployeeID=Employee Id

FirstName=First Name

LastName=Last Name

Age=Age

Education=Education

Salary=Salary

Submit=Submit

employeeList=Employee List

EditEmployee=Edit Employee

Step 13

Create the employee.jsp page for CRUD operations

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<html>
<head>
    <title>Employee Page</title>
    <style type="text/css">
        .empTable  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
        .empTable td{font-family:Arial, sans-serif;font-size:16px;padding:10px 5px;border-
                              style:solid;border-width:2px;overflow:hidden;word-break:normal;border- 
                              color:#ccc;color:#00FF00;background-color:#FF0000;}
        .empTable th{font-family:Arial, sans-serif;font-size:16px;font-weight:normal;padding:10px 
                              5px;border-style:solid;border-width:2px;overflow:hidden;word-break:normal;border-
                              color:#ccc;color:#000000;background-color:#FF4500;}
        .empTable .empTable-4eph{background-color:#C0C0C0}
    </style>
</head>
<body>
 
    <c:if test="${empty employee.employeeId}">
    <h1>
    <spring:message code="AddEmployee"/>
    </h1>
    </c:if>
 
 
<c:url var="addAction" value="/employee/add" ></c:url>
 
<form:form action="${addAction}" modelAttribute="employee">
<table>
    <c:if test="${not empty employee.employeeId}">
    <h1><spring:message code="EditEmployee"/></h1>
    <tr>
        <td>
            <form:label path="employeeId">
                <spring:message code="EmployeeID"/>
            </form:label>
        </td>
        <td>
            <form:input path="employeeId" readonly="true" size="8"  disabled="true" />
            <form:hidden path="employeeId" />
        </td> 
    </tr>
    </c:if>
 
    <tr>
        <td>
            <form:label path="firstName">
                <spring:message code="FirstName"/>
            </form:label>
        </td>
        <td>
            <form:input path="firstName" />
        </td> 
    </tr>
 
    <tr>
        <td>
            <form:label path="lastName">
                <spring:message code="LastName"/>
            </form:label>
        </td>
        <td>
            <form:input path="lastName" />
        </td> 
    </tr>
 
    <tr>
        <td>
            <form:label path="age">
                <spring:message code="Age"/>
            </form:label>
        </td>
        <td>
            <form:input path="age" />
        </td>
    </tr>
 
    <tr>
        <td>
            <form:label path="education">
                <spring:message code="Education"/>
            </form:label>
        </td>
        <td>
            <form:input path="education" />
        </td>
    </tr>
 
    <tr>
        <td>
            <form:label path="salary">
                <spring:message code="Salary"/>
            </form:label>
        </td>
        <td>
            <form:input path="salary" />
        </td>
    </tr>
 
    <tr>
        <td colspan="2">
                <input type="submit"
                    value="<spring:message code="Submit"/>" />
        </td>
    </tr>
 
</table>    
</form:form>
<br>
 
<c:if test="${not empty employeeList}">
<h3><spring:message code="employeeList"/></h3>
    <table class="empTable">
    <tr>
        <th width="80">ID</th>
        <th width="120">First Name</th>
        <th width="120">Last Name</th>
        <th width="120">Age</th>
        <th width="120">Education</th>
        <th width="120">Salary</th>
        <th width="60">Edit</th>
        <th width="60">Delete</th>
    </tr>
 
    <c:forEach items="${employeeList}" var="employee">
        <tr>
            <td>${employee.employeeId}</td>
            <td>${employee.firstName}</td>
            <td>${employee.lastName}</td>
            <td>${employee.age}</td>
            <td>${employee.education}</td>
            <td>${employee.salary}</td>
            <td><a href="<c:url value='/employee/edit/${employee.employeeId}' />" >Edit</a></td>
            <td><a href="<c:url value='employee/remove/${employee.employeeId}' />" >Delete</a></td>
        </tr>
    </c:forEach>
    </table>
</c:if>
</body>
</html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<html>
<head>
	<title>Employee Page</title>
	<style type="text/css">
		.empTable  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
		.empTable td{font-family:Arial, sans-serif;font-size:16px;padding:10px 5px;border-
                              style:solid;border-width:2px;overflow:hidden;word-break:normal;border- 
                              color:#ccc;color:#00FF00;background-color:#FF0000;}
		.empTable th{font-family:Arial, sans-serif;font-size:16px;font-weight:normal;padding:10px 
                              5px;border-style:solid;border-width:2px;overflow:hidden;word-break:normal;border-
                              color:#ccc;color:#000000;background-color:#FF4500;}
		.empTable .empTable-4eph{background-color:#C0C0C0}
	</style>
</head>
<body>

	<c:if test="${empty employee.employeeId}">
	<h1>
	<spring:message code="AddEmployee"/>
	</h1>
	</c:if>


<c:url var="addAction" value="/employee/add" ></c:url>

<form:form action="${addAction}" modelAttribute="employee">
<table>
	<c:if test="${not empty employee.employeeId}">
	<h1><spring:message code="EditEmployee"/></h1>
	<tr>
		<td>
			<form:label path="employeeId">
				<spring:message code="EmployeeID"/>
			</form:label>
		</td>
		<td>
			<form:input path="employeeId" readonly="true" size="8"  disabled="true" />
			<form:hidden path="employeeId" />
		</td> 
	</tr>
	</c:if>

	<tr>
		<td>
			<form:label path="firstName">
				<spring:message code="FirstName"/>
			</form:label>
		</td>
		<td>
			<form:input path="firstName" />
		</td> 
	</tr>

	<tr>
		<td>
			<form:label path="lastName">
				<spring:message code="LastName"/>
			</form:label>
		</td>
		<td>
			<form:input path="lastName" />
		</td> 
	</tr>

	<tr>
		<td>
			<form:label path="age">
				<spring:message code="Age"/>
			</form:label>
		</td>
		<td>
			<form:input path="age" />
		</td>
	</tr>

	<tr>
		<td>
			<form:label path="education">
				<spring:message code="Education"/>
			</form:label>
		</td>
		<td>
			<form:input path="education" />
		</td>
	</tr>

	<tr>
		<td>
			<form:label path="salary">
				<spring:message code="Salary"/>
			</form:label>
		</td>
		<td>
			<form:input path="salary" />
		</td>
	</tr>

	<tr>
		<td colspan="2">
				<input type="submit"
					value="<spring:message code="Submit"/>" />
		</td>
	</tr>

</table>	
</form:form>
<br>

<c:if test="${not empty employeeList}">
<h3><spring:message code="employeeList"/></h3>
	<table class="empTable">
	<tr>
		<th width="80">ID</th>
		<th width="120">First Name</th>
		<th width="120">Last Name</th>
		<th width="120">Age</th>
		<th width="120">Education</th>
		<th width="120">Salary</th>
		<th width="60">Edit</th>
		<th width="60">Delete</th>
	</tr>

	<c:forEach items="${employeeList}" var="employee">
		<tr>
			<td>${employee.employeeId}</td>
			<td>${employee.firstName}</td>
			<td>${employee.lastName}</td>
			<td>${employee.age}</td>
			<td>${employee.education}</td>
			<td>${employee.salary}</td>
			<td><a href="<c:url value='/employee/edit/${employee.employeeId}' />" >Edit</a></td>
			<td><a href="<c:url value='employee/remove/${employee.employeeId}' />" >Delete</a></td>
		</tr>
	</c:forEach>
	</table>
</c:if>
</body>
</html>

Step 14

Build and deploy the project

Step 15

Let’s see the output of all CRUD operations

Access below url

http://localhost:8080/SpringMVCHibernateCRUD/employees

springmvc_hibernate_crud_output1

Since we don’t have any employees in the database, we get a form to add new employee details

Step 16

Fill the employee details and Submit


springmvc_hibernate_crud_fill_emp_data_output2

Add 2 more employees in the same way and check the below output

springmvc_hibernate_crud_fill_emp_data_output3

Update the employee by editing the details

Click on edit on employee row whose id is ‘3’, below form will open with prepopulated data

Updating the age to 35

springmvc_hibernate_crud_edit_emp_data_output4

After submission, we can see the updated age in the result list

springmvc_hibernate_crud_edit_emp_data_output5

Delete the employee

Click on delete on any one of the employee and check the result

springmvc_hibernate_crud_delete_emp_data_output6a

After deletion, we can see that i have deleted one employee whose id is ‘3’

springmvc_hibernate_crud_delete_emp_data_output6

Download this project SpringMVCHibernateCRUD.zip

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on