Hibernate CRUD operations with Spring MVC and MYSQL

Let’s see the CRUD operations in Hibernate with Spring MVC and MYSQL


Tools and Technologies used

Java

Spring

Eclipse

Maven

Hibernate

MYSQL


Step 1

First create the database schema and tables to perform the CRUD operations

Copy and run the below scripts in the MySQL command window or MySQL workbench(GUI Tool) –> SQL Editor

I am using Command window to run these scripts
Go to MySql bin directory under MySql installation path E:\MySql_Install\bin

Issue the following command

mysql –u root –p

Enter the password

mysql_command_line2

Now run these scripts

  1. create database javainsimpleway;
create database javainsimpleway;

  1. use javainsimpleway;
use javainsimpleway;

  1. CREATE TABLE users (
  2.   Id int(15) NOT NULL AUTO_INCREMENT,
  3.   FirstName varchar(50),
  4.   LastName varchar(50),
  5.   Dob date,
  6.   Email varchar(100),
  7.   PRIMARY KEY (Id)
  8. );
CREATE TABLE users (
  Id int(15) NOT NULL AUTO_INCREMENT,
  FirstName varchar(50),
  LastName varchar(50),
  Dob date,
  Email varchar(100),
  PRIMARY KEY (Id)
);


Check the table created using below command

  1. desc users;
desc users;


mysql_create_users_table3

Step 2

Create a Java Maven web project in eclipse and setup Hibernate

Please refer this article on how to do it.

Project Structure


hibernate_spring_crud_proj_stru1
hibernate_spring_crud_proj_stru2

Step 3

Update pom.xml with spring dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4.         http://maven.apache.org/maven-v4_0_0.xsd">
  5.     <modelVersion>4.0.0</modelVersion>
  6.     <groupId>HibernateCRUDSpringMVC</groupId>
  7.     <artifactId>HibernateCRUDSpringMVC</artifactId>
  8.     <packaging>war</packaging>
  9.     <version>0.0.1-SNAPSHOT</version>
  10.     <name>HibernateCRUDSpringMVC Maven Webapp</name>
  11.     <url>http://maven.apache.org</url>
  12.     <properties>
  13.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  14.     </properties>
  15.     <dependencies>
  16.         <dependency>
  17.             <groupId>junit</groupId>
  18.             <artifactId>junit</artifactId>
  19.             <version>3.8.1</version>
  20.             <scope>test</scope>
  21.         </dependency>
  22.         <dependency>
  23.             <groupId>javax.servlet</groupId>
  24.             <artifactId>servlet-api</artifactId>
  25.             <version>2.5</version>
  26.         </dependency>
  27.         <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
  28.         <dependency>
  29.             <groupId>org.springframework</groupId>
  30.             <artifactId>spring-webmvc</artifactId>
  31.             <version>${org.springframework.version}</version>
  32.         </dependency>
  33.        
  34.         <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
  35. <dependency>
  36.     <groupId>org.springframework</groupId>
  37.     <artifactId>spring-tx</artifactId>
  38.     <version>${org.springframework.version}</version>
  39. </dependency>
  40. <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
  41. <dependency>
  42.     <groupId>org.springframework</groupId>
  43.     <artifactId>spring-jdbc</artifactId>
  44.     <version>${org.springframework.version}</version>
  45. </dependency>
  46. <!-- https://mvnrepository.com/artifact/jstl/jstl -->
  47. <dependency>
  48.     <groupId>jstl</groupId>
  49.     <artifactId>jstl</artifactId>
  50.     <version>1.2</version>
  51. </dependency>
  52.  
  53.     <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
  54. <dependency>
  55.     <groupId>org.springframework</groupId>
  56.     <artifactId>spring-orm</artifactId>
  57.     <version>${org.springframework.version}</version>
  58. </dependency>
  59. <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
  60. <dependency>
  61.     <groupId>org.springframework</groupId>
  62.     <artifactId>spring-core</artifactId>
  63.     <version>${org.springframework.version}</version>
  64. </dependency>
  65.  
  66. <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
  67. <dependency>
  68.     <groupId>org.springframework</groupId>
  69.     <artifactId>spring-web</artifactId>
  70.     <version>${org.springframework.version}</version>
  71. </dependency>
  72.  
  73. <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
  74. <dependency>
  75.     <groupId>org.springframework</groupId>
  76.     <artifactId>spring-context</artifactId>
  77.     <version>${org.springframework.version}</version>
  78. </dependency>
  79.  
  80.         <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
  81.         <dependency>
  82.             <groupId>org.hibernate</groupId>
  83.             <artifactId>hibernate-core</artifactId>
  84.             <version>5.2.6.Final</version>
  85.         </dependency>
  86.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  87.         <dependency>
  88.             <groupId>mysql</groupId>
  89.             <artifactId>mysql-connector-java</artifactId>
  90.             <version>6.0.5</version>
  91.         </dependency>
  92.     </dependencies>
  93.     <build>
  94.         <finalName>HibernateCRUDSpringMVC</finalName>
  95.     </build>
  96. </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>HibernateCRUDSpringMVC</groupId>
	<artifactId>HibernateCRUDSpringMVC</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>HibernateCRUDSpringMVC 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>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

	<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${org.springframework.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${org.springframework.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework.version}</version>
</dependency>

		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>HibernateCRUDSpringMVC</finalName>
	</build>
</project>


We have added all the required dependencies for Spring and hibernate in the above pom.xml file.

Step 4

Create the hibernate configuration file under src/main/resources folder

hibernate.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8.    <session-factory>
  9.  
  10.        <!-- JDBC connection pool (using the built-in) -->
  11.        <property name="connection.pool_size">1</property>
  12.  
  13.        <!-- SQL dialect -->
  14.        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  15.  
  16.        <!-- Disable the second-level cache -->
  17.        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  18.  
  19.        <!-- Echo all executed SQL to stdout -->
  20.        <property name="show_sql">true</property>
  21.        
  22.        <!-- Format the generated Sql -->
  23.        <property name="format_sql">true</property>
  24.  
  25.        <!-- Dont Drop and re-create the database schema on startup,Just update it -->
  26.        <property name="hbm2ddl.auto">update</property>
  27.  
  28.        <mapping resource="com/kb/mapping/user.hbm.xml"/>
  29.  
  30.    </session-factory>
  31.  
  32. </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
   <session-factory>
 
       <!-- JDBC connection pool (using the built-in) -->
       <property name="connection.pool_size">1</property>
 
       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
       <!-- Disable the second-level cache -->
       <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>
       
       <!-- Format the generated Sql -->
       <property name="format_sql">true</property>
 
       <!-- Dont Drop and re-create the database schema on startup,Just update it -->
       <property name="hbm2ddl.auto">update</property>
 
       <mapping resource="com/kb/mapping/user.hbm.xml"/>
 
   </session-factory>
 
</hibernate-configuration>


We have defined the entire database configuration in this file

hbm2ddl.auto property is defined in the config file which helps in automatic creation of tables in the database based on the mapping.

We have also provided the mapping resource file location using < mapping > tag.

Step 5

Create a User model class under src/main/java/com/kb/model package

  1. package com.kb.model;
  2.  
  3. import java.util.Date;
  4.  
  5. public class User {
  6.     private int id;
  7.     private String firstName;
  8.     private String lastName;
  9.     private Date dob;
  10.     private String email;
  11.     public int getId() {
  12.         return id;
  13.     }
  14.     public void setId(int id) {
  15.         this.id = id;
  16.     }
  17.     public String getFirstName() {
  18.         return firstName;
  19.     }
  20.     public void setFirstName(String firstName) {
  21.         this.firstName = firstName;
  22.     }
  23.     public String getLastName() {
  24.         return lastName;
  25.     }
  26.     public void setLastName(String lastName) {
  27.         this.lastName = lastName;
  28.     }
  29.     public Date getDob() {
  30.         return dob;
  31.     }
  32.     public void setDob(Date dob) {
  33.         this.dob = dob;
  34.     }
  35.     public String getEmail() {
  36.         return email;
  37.     }
  38.     public void setEmail(String email) {
  39.         this.email = email;
  40.     }
  41. }
package com.kb.model;

import java.util.Date;

public class User {
	private int id;
    private String firstName;
    private String lastName;
    private Date dob;
    private String email;
	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 Date getDob() {
		return dob;
	}
	public void setDob(Date dob) {
		this.dob = dob;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

Step 6

Create the mapping file for User Model under src/main/resources/com/kb/mapping folder

user.hbm.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5.  
  6. <hibernate-mapping>
  7.     <class name="com.kb.model.User" table="users">
  8.         <id name="id" type="int" column="Id">
  9.             <generator class="increment" />
  10.         </id>
  11.         <property name="firstName">
  12.             <column name="FirstName" />
  13.         </property>
  14.         <property name="lastName">
  15.             <column name="LastName" />
  16.         </property>
  17.         <property name="dob">
  18.             <column name="Dob" />
  19.         </property>
  20.         <property name="email">
  21.             <column name="Email" />
  22.         </property>
  23.     </class>
  24. </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.kb.model.User" table="users">
        <id name="id" type="int" column="Id">
            <generator class="increment" />
        </id>
        <property name="firstName">
            <column name="FirstName" />
        </property>
        <property name="lastName">
            <column name="LastName" />
        </property>
        <property name="dob">
            <column name="Dob" />
        </property>
        <property name="email">
            <column name="Email" />
        </property>
    </class>
</hibernate-mapping>


In the above mapping file, we have provided mapping of User class to Users table and each attribute of User class to their respective columns.

Step 7

Create UserDao interface and implementation class to interact with Database

UserDao.java

  1. package com.kb.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.model.User;
  6.  
  7. public interface UserDao {
  8.    
  9.      public void addUser(User user);
  10.      
  11.      public List<User> getAllUsers();
  12.      
  13.      public User getUserById(int userid);
  14.      
  15.      public void updateUser(User user);
  16.      
  17.      public void deleteUser(int userid);
  18.  
  19. }
package com.kb.dao;

import java.util.List;

import com.kb.model.User;

public interface UserDao {
	
	 public void addUser(User user);
	 
	 public List<User> getAllUsers();
	 
	 public User getUserById(int userid);
	 
	 public void updateUser(User user);
	 
	 public void deleteUser(int userid);

}


UserDaoImpl.java

  1. package com.kb.dao.impl;
  2.  
  3. import java.util.List;
  4.  
  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.query.Query;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Repository;
  10.  
  11. import com.kb.dao.UserDao;
  12. import com.kb.model.User;
  13.  
  14. @Repository
  15. public class UserDaoImpl implements UserDao {
  16.  
  17.     @Autowired
  18.     private SessionFactory sessionFactory;
  19.  
  20.     // Create of CRUD
  21.     public void addUser(User user) {
  22.         sessionFactory.getCurrentSession().save(user);
  23.     }
  24.  
  25.     // Read of CRUD
  26.     @SuppressWarnings("unchecked")
  27.     public List<User> getAllUsers() {
  28.         return sessionFactory.getCurrentSession().createQuery("from User").getResultList();
  29.     }
  30.  
  31.     // Read of CRUD
  32.     public User getUserById(int userid) {
  33.  
  34.         Session session = sessionFactory.getCurrentSession();
  35.         User user = null;
  36.         String hqlQuery = "from User where id = :id";
  37.         @SuppressWarnings("rawtypes")
  38.         Query query = session.createQuery(hqlQuery);
  39.         query.setParameter("id", userid);
  40.         user = (User) query.getSingleResult();
  41.         return user;
  42.     }
  43.  
  44.     // Update of CRUD
  45.     public void updateUser(User user) {
  46.         sessionFactory.getCurrentSession().update(user);
  47.     }
  48.  
  49.     // Delete of CRUD
  50.     public void deleteUser(int userid) {
  51.  
  52.         User user = (User) sessionFactory.getCurrentSession().load(User.class, userid);
  53.         if (null != user) {
  54.             sessionFactory.getCurrentSession().delete(user);
  55.         }
  56.  
  57.     }
  58.  
  59. }
package com.kb.dao.impl;

import java.util.List;

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

import com.kb.dao.UserDao;
import com.kb.model.User;

@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	// Create of CRUD
	public void addUser(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

	// Read of CRUD
	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
		return sessionFactory.getCurrentSession().createQuery("from User").getResultList();
	}

	// Read of CRUD
	public User getUserById(int userid) {

		Session session = sessionFactory.getCurrentSession();
		User user = null;
		String hqlQuery = "from User where id = :id";
		@SuppressWarnings("rawtypes")
		Query query = session.createQuery(hqlQuery);
		query.setParameter("id", userid);
		user = (User) query.getSingleResult();
		return user;
	}

	// Update of CRUD
	public void updateUser(User user) {
		sessionFactory.getCurrentSession().update(user);
	}

	// Delete of CRUD
	public void deleteUser(int userid) {

		User user = (User) sessionFactory.getCurrentSession().load(User.class, userid);
		if (null != user) {
			sessionFactory.getCurrentSession().delete(user);
		}

	}

}

Step 8

Create UserService interface and implementation class to interact with DAO layer

UserService.java

  1. package com.kb.service;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.model.User;
  6.  
  7. public interface UserService {
  8.    
  9.     public void addUser(User user);
  10.  
  11.     public List<User> getAllUsers();
  12.  
  13.     public User getUserById(int userid);
  14.  
  15.     public void updateUser(User user);
  16.  
  17.     public void deleteUser(int userid);
  18.  
  19. }
package com.kb.service;

import java.util.List;

import com.kb.model.User;

public interface UserService {
	
	public void addUser(User user);

	public List<User> getAllUsers();

	public User getUserById(int userid);

	public void updateUser(User user);

	public void deleteUser(int userid);

}


UserServiceImpl.java

  1. package com.kb.service.impl;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.transaction.annotation.Transactional;
  8.  
  9. import com.kb.dao.UserDao;
  10. import com.kb.model.User;
  11. import com.kb.service.UserService;
  12.  
  13. @Service
  14. public class UserServiceImpl implements UserService {
  15.  
  16.     @Autowired
  17.     private UserDao userDao;
  18.  
  19.     // Create of CRUD
  20.     @Transactional
  21.     public void addUser(User user) {
  22.         userDao.addUser(user);
  23.     }
  24.  
  25.     // Read of CRUD
  26.     @Transactional
  27.     public List<User> getAllUsers() {
  28.         return userDao.getAllUsers();
  29.     }
  30.  
  31.     // Read of CRUD
  32.     @Transactional
  33.     public User getUserById(int userid) {
  34.         return userDao.getUserById(userid);
  35.     }
  36.  
  37.     // Update of CRUD
  38.     @Transactional
  39.     public void updateUser(User user) {
  40.         userDao.updateUser(user);
  41.     }
  42.  
  43.     // Delete of CRUD
  44.     @Transactional
  45.     public void deleteUser(int userid) {
  46.         userDao.deleteUser(userid);
  47.     }
  48.  
  49.     public UserDao getUserDao() {
  50.         return userDao;
  51.     }
  52.  
  53.     public void setUserDao(UserDao userDao) {
  54.         this.userDao = userDao;
  55.     }
  56.  
  57. }
package com.kb.service.impl;

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.UserDao;
import com.kb.model.User;
import com.kb.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	// Create of CRUD
	@Transactional
	public void addUser(User user) {
		userDao.addUser(user);
	}

	// Read of CRUD
	@Transactional
	public List<User> getAllUsers() {
		return userDao.getAllUsers();
	}

	// Read of CRUD
	@Transactional
	public User getUserById(int userid) {
		return userDao.getUserById(userid);
	}

	// Update of CRUD
	@Transactional
	public void updateUser(User user) {
		userDao.updateUser(user);
	}

	// Delete of CRUD
	@Transactional
	public void deleteUser(int userid) {
		userDao.deleteUser(userid);
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}

Step 9

Create the controller class

  1. package com.kb.controller;
  2.  
  3. import java.util.Map;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.validation.BindingResult;
  8. import org.springframework.web.bind.annotation.ModelAttribute;
  9. import org.springframework.web.bind.annotation.PathVariable;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12.  
  13. import com.kb.model.User;
  14. import com.kb.service.UserService;
  15.  
  16. @Controller
  17. public class UserController {
  18.  
  19.     @Autowired
  20.     private UserService userService;
  21.  
  22.     @RequestMapping("/home")
  23.     public String listBooks(Map<String, Object> map) {
  24.         map.put("user", new User());
  25.         map.put("userList", userService.getAllUsers());
  26.         return "user";
  27.     }
  28.  
  29.     @RequestMapping(value = "/user/add", method = RequestMethod.POST)
  30.     public String addUser(@ModelAttribute("user") User user, BindingResult result) {
  31.         if (null != user) {
  32.             userService.addUser(user);
  33.         }
  34.         return "redirect:/home";
  35.     }
  36.  
  37.     @RequestMapping("/delete/{userId}")
  38.     public String deleteUser(@PathVariable("userId") int userId) {
  39.         userService.deleteUser(userId);
  40.         return "redirect:/home";
  41.     }
  42.  
  43.     @RequestMapping("/edit/{userId}")
  44.     public String editUser(@PathVariable("userId") int userId, Map<String, Object> map) {
  45.         User user = userService.getUserById(userId);
  46.         // Providing new value for Edit
  47.         user.setFirstName("EditedName");
  48.         userService.updateUser(user);
  49.         map.put("userList", userService.getAllUsers());
  50.         return "redirect:/home";
  51.     }
  52.  
  53.     public UserService getUserService() {
  54.         return userService;
  55.     }
  56.  
  57.     public void setUserService(UserService userService) {
  58.         this.userService = userService;
  59.     }
  60.  
  61. }
package com.kb.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 com.kb.model.User;
import com.kb.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping("/home")
	public String listBooks(Map<String, Object> map) {
		map.put("user", new User());
		map.put("userList", userService.getAllUsers());
		return "user";
	}

	@RequestMapping(value = "/user/add", method = RequestMethod.POST)
	public String addUser(@ModelAttribute("user") User user, BindingResult result) {
		if (null != user) {
			userService.addUser(user);
		}
		return "redirect:/home";
	}

	@RequestMapping("/delete/{userId}")
	public String deleteUser(@PathVariable("userId") int userId) {
		userService.deleteUser(userId);
		return "redirect:/home";
	}

	@RequestMapping("/edit/{userId}")
	public String editUser(@PathVariable("userId") int userId, Map<String, Object> map) {
		User user = userService.getUserById(userId);
		// Providing new value for Edit
		user.setFirstName("EditedName");
		userService.updateUser(user);
		map.put("userList", userService.getAllUsers());
		return "redirect:/home";
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}

Step 10

Create spring configuration file

Spring-mvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xmlns:aop="http://www.springframework.org/schema/aop"
  5.     xmlns:context="http://www.springframework.org/schema/context"
  6.     xmlns:jee="http://www.springframework.org/schema/jee"
  7.     xmlns:lang="http://www.springframework.org/schema/lang"
  8.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  9.     xmlns:p="http://www.springframework.org/schema/p"
  10.     xmlns:tx="http://www.springframework.org/schema/tx"
  11.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  12.                       http://www.springframework.org/schema/beans/spring-beans.xsd
  13.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  14.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  15.     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
  16.     http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
  17.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  18.     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  19.        
  20.     <context:component-scan base-package="com.kb" />
  21.     <mvc:annotation-driven />
  22.  
  23.     <bean id="viewResolver"
  24.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  25.         <property name="prefix" value="/WEB-INF/pages/" />
  26.         <property name="suffix" value=".jsp" />
  27.     </bean>
  28.  
  29.     <bean id="messageSource"
  30.         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  31.         <property name="basename" value="/WEB-INF/messages" />
  32.     </bean>
  33.    
  34.      <bean id="propertyConfigurer"
  35.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
  36.         p:location="/WEB-INF/jdbc.properties" />
  37.        
  38.         <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  39.              <property name="driverClassName" value="${jdbc.driverClassName}"></property>
  40.              <property name="url" value="${jdbc.databaseurl}"></property>
  41.              <property name="username" value="${jdbc.username}"></property>
  42.              <property name="password" value="${jdbc.password}"></property>
  43.        </bean>
  44.  
  45.     <bean id="sessionFactory"
  46.         class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  47.         <property name="dataSource" ref="dataSource" />
  48.         <property name="configLocation">
  49.             <value>classpath:hibernate.cfg.xml</value>
  50.         </property>
  51.     </bean>
  52.    
  53.     <tx:annotation-driven />
  54.  
  55.     <bean id="transactionManager"
  56.         class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  57.         <property name="sessionFactory" ref="sessionFactory" />
  58.     </bean>
  59.        
  60. </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: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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
        
	<context:component-scan base-package="com.kb" />
	<mvc:annotation-driven />

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

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="/WEB-INF/messages" />
	</bean>
	
	 <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />
        
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
             <property name="driverClassName" value="${jdbc.driverClassName}"></property>
             <property name="url" value="${jdbc.databaseurl}"></property>
             <property name="username" value="${jdbc.username}"></property>
             <property name="password" value="${jdbc.password}"></property>
       </bean>
 
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
    </bean>
    
    <tx:annotation-driven />
 
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
        
</beans>


We have defined dataSource bean with all the JDBC connection values.

We have defined SessionFactory bean and injected dataSource to it, we have also provided configuration file location to the SessionFactory to load all the configuration details.

We have also injected the SessionFactory to Transaction to create Spring transaction.

Step 11

Update web.xml with spring dispatcher servlet

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  2.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
  4.         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  5.  
  6.     <display-name>Spring MVC Hibernate CRUD</display-name>
  7.  
  8.     <!-- Spring MVC dispatcher servlet -->
  9.     <servlet>
  10.         <servlet-name>mvc-dispatcher</servlet-name>
  11.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  12.         <init-param>
  13.             <param-name>contextConfigLocation</param-name>
  14.             <param-value>
  15.             /WEB-INF/spring-mvc.xml,
  16.         </param-value>
  17.         </init-param>
  18.         <load-on-startup>1</load-on-startup>
  19.     </servlet>
  20.     <servlet-mapping>
  21.         <servlet-name>mvc-dispatcher</servlet-name>
  22.         <url-pattern>/</url-pattern>
  23.     </servlet-mapping>
  24.  
  25.     <listener>
  26.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  27.     </listener>
  28.  
  29.     <context-param>
  30.         <param-name>contextConfigLocation</param-name>
  31.         <param-value>
  32.             /WEB-INF/spring-mvc.xml,
  33.         </param-value>
  34.     </context-param>
  35.  
  36. </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>Spring MVC Hibernate CRUD</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>

Step 12

Create jdbc.properties file

  1. jdbc.driverClassName=com.mysql.jdbc.Driver
  2. jdbc.databaseurl=jdbc:mysql://localhost:3306/javainsimpleway
  3. jdbc.username=root
  4. jdbc.password=root
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.databaseurl=jdbc:mysql://localhost:3306/javainsimpleway
jdbc.username=root
jdbc.password=root

Step 13

Create view page

user.jsp

  1. <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
  2. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
  3. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  4. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
  5. <html>
  6. <head>
  7.     <title>Spring MVC Hibernate -  CRUD</title>
  8.     <style type="text/css">
  9.         body {
  10.             font-family: Arial;
  11.             font-size: 10px;
  12.             margin: 30px;
  13.         }
  14.         .userTable, .userTable td {
  15.             border-collapse: collapse;
  16.             border: 1px solid #0000FF;
  17.             margin: 2px;
  18.             padding: 2px 2px 2px 10px;
  19.             font-size: 14px;
  20.         }
  21.         .userTable th {
  22.             font-weight: bold;
  23.             font-size: 14px;
  24.             background-color: #5C82FF;
  25.             color: white;
  26.         }
  27.         .userLabel {
  28.             font-family: Arial;
  29.             font-size: 14px;
  30.             font-weight: bold;
  31.         }
  32.         a, a:AFTER {
  33.             color: blue;
  34.         }
  35.     </style>
  36.     <script type="text/javascript">
  37.     function deleteUser(userId){
  38.         if(confirm('Do you want to delete this User ?')){
  39.             var url = 'delete/'+userId;
  40.             window.location.href = url;
  41.         }
  42.     }
  43.     </script>
  44. </head>
  45. <body>
  46.  
  47. <h2>SpringMVC-Hibernate CRUD Application</h2>
  48. <p style="color:green;font-weight:bold;">
  49.  <a href="<c:url value='/home' />"> Add New User</a>
  50. </p>
  51. <c:url var="action" value="/user/add" ></c:url>
  52. <form:form method="post" action="${action}" modelAttribute="user">
  53.     <table>
  54.    
  55.   <c:if test="${not empty user.firstName}">
  56.     <tr>
  57.         <td>
  58.             <form:label path="id" cssClass="userLabel">
  59.                 <spring:message code="label.UserId" />
  60.             </form:label>
  61.         </td>
  62.        
  63.         <td>
  64.             <form:input path="id" readonly="true" size="10"  disabled="true" />
  65.             <form:hidden path="id" />
  66.         </td>
  67.     </tr>
  68.    </c:if>
  69.  
  70.     <tr>
  71.         <td>
  72.             <form:label path="firstName" cssClass="userLabel">
  73.                 <spring:message code="label.FirstName" />
  74.             </form:label>
  75.         </td>
  76.        
  77.         <td>
  78.             <form:input path="firstName" />
  79.         </td>
  80.     </tr>
  81.    
  82.     <tr>
  83.         <td>
  84.             <form:label path="lastName" cssClass="userLabel">
  85.                 <spring:message code="label.LastName" />
  86.             </form:label>
  87.         </td>
  88.        
  89.         <td>
  90.             <form:input path="lastName" />
  91.         </td>
  92.     </tr>
  93.    
  94.     <tr>
  95.         <td>
  96.             <form:label path="dob" cssClass="userLabel">
  97.                 <spring:message code="label.DOB" />
  98.             </form:label>
  99.         </td>
  100.        
  101.         <td>
  102.             <form:input path="dob" />
  103.         </td>
  104.     </tr>
  105.    
  106.     <tr>
  107.         <td>
  108.             <form:label path="email" cssClass="userLabel">
  109.                 <spring:message code="label.Email" />
  110.             </form:label>
  111.         </td>
  112.        
  113.         <td>
  114.             <form:input path="email" />
  115.         </td>
  116.     </tr>
  117.    
  118.     <tr>
  119.         <td colspan="2">
  120.                 <input type="submit"
  121.                     value="<spring:message code="label.AddUser"/>" />
  122.         </td>
  123.     </tr>
  124.  
  125. </table>    
  126. </form:form>
  127.  
  128. <h3>List of Users</h3>
  129.  
  130. <c:if test="${not empty userList}">
  131.     <table class="userTable">
  132.     <tr>
  133.         <th width="160">First Name</th>
  134.         <th width="60">Last Name</th>
  135.         <th width="80">Dob</th>
  136.         <th width="60">Email</th>
  137.          <th width="100">Action</th>
  138.     </tr>
  139.     <c:forEach items="${userList}" var="user">
  140.         <tr>
  141.             <td>
  142.       <a href="<c:url value='/edit/${user.id}' />" >${user.firstName}</a>
  143.       </td>
  144.             <td>${user.lastName}</td>
  145.             <td><fmt:formatDate pattern="yyyy-MM-dd"
  146.             value="${user.dob}" /> </td>
  147.             <td>${user.email}</td>
  148.             <td><a href="<c:url value='/edit/${user.id}' />"> <spring:message code="label.EditUser"/> ></a>
  149.             <a href="#" onclick="javascript:deleteUser(${user.id})"> <spring:message code="label.Delete"/> ></a>
  150.             </td>
  151.         </tr>
  152.     </c:forEach>
  153.     </table>
  154. </c:if>
  155.  
  156. </body>
  157. </html>
<%@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"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>Spring MVC Hibernate -  CRUD</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10px;
            margin: 30px;
        }
        .userTable, .userTable td {
            border-collapse: collapse;
            border: 1px solid #0000FF;
            margin: 2px;
            padding: 2px 2px 2px 10px;
            font-size: 14px;
        }
        .userTable th {
            font-weight: bold;
            font-size: 14px;
            background-color: #5C82FF;
            color: white;
        }
        .userLabel {
            font-family: Arial;
            font-size: 14px;
            font-weight: bold;
        }
        a, a:AFTER {
            color: blue;
        }
    </style>
    <script type="text/javascript">
    function deleteUser(userId){
        if(confirm('Do you want to delete this User ?')){
            var url = 'delete/'+userId;
            window.location.href = url;
        }
    }
    </script>
</head>
<body>
 
<h2>SpringMVC-Hibernate CRUD Application</h2>
<p style="color:green;font-weight:bold;">
 <a href="<c:url value='/home' />"> Add New User</a>
</p>
<c:url var="action" value="/user/add" ></c:url>
<form:form method="post" action="${action}" modelAttribute="user">
    <table>
   
  <c:if test="${not empty user.firstName}">
    <tr>
        <td>
            <form:label path="id" cssClass="userLabel">
                <spring:message code="label.UserId" />
            </form:label>
        </td>
        
        <td>
            <form:input path="id" readonly="true" size="10"  disabled="true" />
            <form:hidden path="id" />
        </td> 
    </tr>
   </c:if>

    <tr>
        <td>
            <form:label path="firstName" cssClass="userLabel">
                <spring:message code="label.FirstName" />
            </form:label>
        </td>
       
        <td>
            <form:input path="firstName" />
        </td> 
    </tr>
   
    <tr>
        <td>
            <form:label path="lastName" cssClass="userLabel">
                <spring:message code="label.LastName" />
            </form:label>
        </td>
        
        <td>
            <form:input path="lastName" />
        </td>
    </tr>
    
    <tr>
        <td>
            <form:label path="dob" cssClass="userLabel">
                <spring:message code="label.DOB" />
            </form:label>
        </td>
        
        <td>
            <form:input path="dob" />
        </td>
    </tr>
   
    <tr>
        <td>
            <form:label path="email" cssClass="userLabel">
                <spring:message code="label.Email" />
            </form:label>
        </td>
       
        <td>
            <form:input path="email" />
        </td>
    </tr>
   
    <tr>
        <td colspan="2">
                <input type="submit"
                    value="<spring:message code="label.AddUser"/>" />
        </td>
    </tr>

</table>    
</form:form>

<h3>List of Users</h3>

<c:if test="${not empty userList}">
    <table class="userTable">
    <tr>
        <th width="160">First Name</th>
        <th width="60">Last Name</th>
        <th width="80">Dob</th>
        <th width="60">Email</th>
         <th width="100">Action</th>
    </tr>
    <c:forEach items="${userList}" var="user">
        <tr>
            <td>
      <a href="<c:url value='/edit/${user.id}' />" >${user.firstName}</a>
      </td>
            <td>${user.lastName}</td>
            <td><fmt:formatDate pattern="yyyy-MM-dd" 
            value="${user.dob}" /> </td>
            <td>${user.email}</td>
            <td><a href="<c:url value='/edit/${user.id}' />"> <spring:message code="label.EditUser"/> ></a>
            <a href="#" onclick="javascript:deleteUser(${user.id})"> <spring:message code="label.Delete"/> ></a>
            </td>
        </tr>
    </c:forEach>
    </table>
</c:if>
  
</body>
</html>

Step 14

Create messages.properties file

  1. label.UserId =Id
  2. label.FirstName =First Name
  3. label.LastName=Last Name
  4. label.DOB=Date Of Birth
  5. label.Email=Email
  6. label.EditUser=Edit
  7. label.AddUser=Add
  8. label.Delete=Delete
label.UserId =Id
label.FirstName =First Name
label.LastName=Last Name
label.DOB=Date Of Birth
label.Email=Email
label.EditUser=Edit
label.AddUser=Add
label.Delete=Delete

Step 15

Build the project and deploy the war file into Tomcat webapps folder

Step 16

Access the below URL and perform the CRUD operations

http://localhost:8080/HibernateCRUDSpringMVC/home

hibernate_spring_crud_output1

Add operation

Add user details and click on Add

hibernate_spring_crud_output2

We can see that new user has been added
Add as many users as you want.

Read operation

I have added 2 users and it’s as below

hibernate_spring_crud_output3

Update Operation

I am updating John user by clicking on Edit on John’s row

hibernate_spring_crud_output4

Delete operation

I am deleting the edited user now

hibernate_spring_crud_output5

Click OK on confirmation and we can see that record has been deleted

hibernate_spring_crud_output6

Download this project HibernateCRUDSpringMVC.zip

About the Author

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