Spring MVC and Hibernate CRUD example

Here is the example which explains how the Spring and Hibernate work together in a web application which is developed using the Spring MVC. 

First, we need to create the Spring MVC project. For this, we will start from configuring the web.xml file as following:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	
	<servlet>
		<servlet-name>spring-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
  <servlet-mapping>
		<servlet-name>spring-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

 

Then, need to create the Spring MVC configuration file. As we named the DisplatcherServlet as spring-displatcher, this file is created with the name "spring-dispatcher-server.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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<mvc:annotation-driven />
	<context:component-scan base-package="user" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
	</bean>

</beans>

Now, create the controller UserController.java

package user;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@RequestMapping("/")
	public String welcomeUser() {
		return "home.jsp";
	}

	@RequestMapping(value="/register",method=RequestMethod.GET)
	public String registrationOpen() {
		return "Registration.jsp";
	}
	

	@RequestMapping(value="/register",method=RequestMethod.POST)
	public @ResponseBody String registrationProcess(Contact contact ) {
		
		System.out.println(contact);
		sessionFactory.getCurrentSession().save(contact);
		
		return "You have registered successfuly.";
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

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

}

Create a view file Registration.jsp in WEB-INF/views folder.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="register" method="post">
	Name : <input type = "text" name="name"/><br/>
	Mobile : <input type="text" name="mobile"/><br/>
	Email :<input type="text" name="email"/><br/>
	<input type="submit">
	
</form>
</body>
</html>

 

Here, we are using the java based spring configurations so create the file applicationConfig.java

package user;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@EnableTransactionManagement
@Configuration
public class applicationConfig {

	 @Bean
	   public DataSource dataSource() {
	      BasicDataSource dataSource = new BasicDataSource();
	      dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	      dataSource.setUrl("jdbc:mysql://localhost/springdemo");
	      dataSource.setUsername("root");
	      dataSource.setPassword("");
	      return dataSource;
	   }
	 
	 @Bean
	   public LocalSessionFactoryBean sessionFactory() {
	      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
	      sessionFactory.setDataSource(dataSource());
	      sessionFactory.setPackagesToScan(new String[] { "user" });

	      Properties properties = new Properties();
	      properties.put("hibernate.show_sql", "true");
	      properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
	      properties.put("hibernate.hbm2ddl.auto", "create");
	      
	      sessionFactory.setHibernateProperties(properties);

	      return sessionFactory;
	   }
	 
	 @Autowired
	 @Bean(name = "transactionManager")
	 public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
	     HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
	     return transactionManager;
	 }
	
}

Create the contact bean class.

package user;

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

@Entity
public class Contact {
	@Id
	@GeneratedValue
	private int id;
	private String name;
	private String mobile;
	private String email;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getEmail() {
		return email;
	}

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

	@Override
	public String toString() {
		return "Contact [name=" + name + ", mobile=" + mobile + ", email=" + email + "]";
	}

	public int getId() {
		return id;
	}

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