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
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
Now run these scripts
- create database javainsimpleway;
create database javainsimpleway;
- use javainsimpleway;
use javainsimpleway;
- CREATE TABLE users (
- Id int(15) NOT NULL AUTO_INCREMENT,
- FirstName varchar(50),
- LastName varchar(50),
- Dob date,
- Email varchar(100),
- PRIMARY KEY (Id)
- );
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
- desc users;
desc users;
Step 2
Create a Java Maven web project in eclipse and setup Hibernate
Please refer this article on how to do it.
Project Structure
Step 3
Update pom.xml with spring dependencies
- <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>
<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
- <?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>
<?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
- 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;
- }
- }
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
- <?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>
<?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
- 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);
- }
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
- 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);
- }
- }
- }
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
- 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);
- }
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
- 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;
- }
- }
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
- 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;
- }
- }
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
- <?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>
<?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
- <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>
<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
- jdbc.driverClassName=com.mysql.jdbc.Driver
- jdbc.databaseurl=jdbc:mysql://localhost:3306/javainsimpleway
- jdbc.username=root
- 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
- <%@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>
<%@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
- 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
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
Add operation
Add user details and click on Add
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
Update Operation
I am updating John user by clicking on Edit on John’s row
Delete operation
I am deleting the edited user now
Click OK on confirmation and we can see that record has been deleted
can you please explain me how to do above example without using XML files