Spring MVC + Hibernate + MySQL + Maven CRUD Example

By Arvind Rai, June 25, 2019
This page will walk through Spring MVC, Hibernate, MySQL, Maven CRUD integration using annotation and XML configuration. In MySQL we are creating a person table. We are integrating spring with hibernate to interact with database using Spring HibernateTemplate. We are creating a service and transactional DAO class. In our example we are performing create, read, update and delete (CRUD) operation. We are validating our form input fields using Spring MVC validation. To submit the form we are using jQuery for adding and updating person. Here on this page, we are providing annotation as well as XML configuration. In annotation approach spring MVC and Hibernate configuration are being performed in JavaConfig. In XML approach Spring MVC and Hibernate configuration will be done using XML. For validation error we are externalizing messages in property file to achieve i18. We are also using property file for data source and Hibernate configuration. Now find the complete example.

Software Used

We are using below software in our example.
1. Java 8
2. Spring 4.2.5.RELEASE
3. Hibernate 4
4. Maven 3
5. Tomcat 8
6. MySQL 5
7. Eclipse
8. jQuery 2

Spring MVC Hibernate Integration using Annotation

Here we will provide Spring MVC Hibernate integration using annotation. Spring MVC and Hibernate configurations are being performed in JavaConfig.

Maven to Resolve JAR Dependencies using Spring Boot

Find the maven file. We are using spring boot to resolve spring JAR dependencies.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>com.concretepage.app</groupId>
  <artifactId>spring4-mvc</artifactId>
  <version>1</version>
  <packaging>war</packaging>      
  <name>SpringMVC</name>
  <properties>	
	<context.path>spring-mvc</context.path>
  </properties>
  <dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
		<version>1.3.3.RELEASE</version>
	</dependency>
	<dependency>
		<groupId> org.springframework.boot </groupId>
		<artifactId>spring-boot-starter-data-jpa </artifactId>
		<version>1.3.3.RELEASE </version>
	</dependency>	
	<dependency>
		<groupId>mysql</groupId>
		<artifactId> mysql-connector-java </artifactId>
		<version>5.1.31</version>
	</dependency>			
	<dependency>
	    <groupId>org.apache.commons</groupId>
	    <artifactId>commons-dbcp2</artifactId>
	    <version>2.1.1</version>
	</dependency>
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>	
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-tomcat</artifactId>
		<version>1.3.3.RELEASE</version>
		<scope>provided</scope>
	</dependency>
	<dependency>
	        <groupId>org.apache.tomcat.embed</groupId>
	        <artifactId>tomcat-embed-el</artifactId>
	        <version>8.0.32</version>
	        <scope>provided</scope>
	</dependency>
  </dependencies>
  <build>
	  <plugins>
		  <plugin>
			  <groupId>org.apache.maven.plugins</groupId>
			  <artifactId>maven-war-plugin</artifactId>
			  <version>2.4</version>
			  <configuration>
				 <warName>${context.path}</warName>
			  </configuration>
		  </plugin>
	  </plugins>
   </build>
 </project> 

Annotation based Project Structure in Eclipse

Find the print screen of annotation based project structure in eclipse.
Spring 4 MVC + Hibernate 4 + MySQL + Maven CRUD Integration using Annotation and XML with Tomcat 8 and Spring Boot Example

Database Table Creation using MySQL

Find the database table created in MySQL.
CREATE DATABASE IF NOT EXISTS 
USE `concretepage`;

CREATE TABLE IF NOT EXISTS `person` (
  `pid` int(5) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `gender` char(1) NOT NULL,
  `city` varchar(100) NOT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

INSERT INTO `person` (`pid`, `username`, `password`, `age`, `gender`, `city`) VALUES
	(1, 'sriram ', 'ram12345', 30, 'M', 'Ghaziabad'),
	(2, 'seeta', 'seeta123', 28, 'F', 'Allahabad'); 

Java Configuration for Hibernate Integration

Find the JavaConfig to configure hibernate.
DBConfig.java
package com.concretepage.config;
import java.io.IOException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.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.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration 
@EnableTransactionManagement
@PropertySource("classpath:database.properties")
public class DBConfig {
        @Autowired
        private Environment env;
	@Bean
	public HibernateTemplate hibernateTemplate() {
		return new HibernateTemplate(sessionFactory());
	}
	@Bean
	public SessionFactory sessionFactory() {
		LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
		lsfb.setDataSource(getDataSource());
		lsfb.setPackagesToScan("com.concretepage.entity");
		lsfb.setHibernateProperties(hibernateProperties());
		try {
			lsfb.afterPropertiesSet();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lsfb.getObject();
	}
	@Bean
	public DataSource getDataSource() {
	    BasicDataSource dataSource = new BasicDataSource();
	    dataSource.setDriverClassName(env.getProperty("database.driver"));
	    dataSource.setUrl(env.getProperty("database.url"));
	    dataSource.setUsername(env.getProperty("database.root"));
	    dataSource.setPassword(env.getProperty("database.password"));
	    return dataSource;
	}
	@Bean
	public HibernateTransactionManager hibTransMan(){
		return new HibernateTransactionManager(sessionFactory());
	}
        private Properties hibernateProperties() {
            Properties properties = new Properties();
            properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
            properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
            properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
            return properties;        
       }	
} 

BasicDataSource : It implements javax.sql.DataSourc and is used for basic requirements.
PropertySource : Annotation to use configuration file.
Environment : It represents the application environment using which we can fetch property values.
HibernateTemplate : Helper class to execute hibernate methods.
HibernateTransactionManager : It binds a hibernate session from the specified factory to a thread.
LocalSessionFactoryBean : It creates hibernate SessionFactory.
EnableTransactionManagement : It enables annotation driven transaction management in spring.

Now find the database property file.
database.properties
database.driver = com.mysql.jdbc.Driver
database.url = jdbc:mysql://localhost:3306/concretepage
database.root = root
database.password =

hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto = update
hibernate.show_sql = true 

Spring MVC Java Configuration

Find the JavaConfig to configure Spring MVC.
AppConfig.java
package com.concretepage.config;  
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration 
@ComponentScan("com.concretepage") 
@Import(DBConfig.class)
@EnableWebMvc   
public class AppConfig extends WebMvcConfigurerAdapter  {   
    @Bean  
    public InternalResourceViewResolver viewResolver() {  
	    InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
            resolver.setPrefix("/WEB-INF/view/");  
            resolver.setSuffix(".jsp");
            return resolver;  
    }
    @Bean 
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/i18/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
    @Bean
    public LocaleResolver localeResolver(){
		CookieLocaleResolver resolver = new CookieLocaleResolver();
		resolver.setDefaultLocale(new Locale("en"));
		resolver.setCookieName("myLocaleCookie");
		resolver.setCookieMaxAge(4800);
		return resolver;
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
		LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
		interceptor.setParamName("mylocale");
		registry.addInterceptor(interceptor);
    }  
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	registry.addResourceHandler("/app-resources/**").addResourceLocations("/resources/");
    }    
} 

ReloadableResourceBundleMessageSource : It is MessageSource implementation which accesses resources using specified basename.
ResourceHandlerRegistry : It serves static resources. We need to configure mapping URL for the actual URL.
CookieLocaleResolver : It helps in stateless application to resolve locate. It sends back a cookie to the user in the form of time zone etc to resolve locale.
InternalResourceViewResolver : It has prefix and suffix property that is used to access the file.

Web Application Initializer

Find the web application initializer. It is supported by Servlet 3 and we need to use web.xml.
WebAppInitializer.java
package com.concretepage.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { AppConfig.class };
	}
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
} 


Create DAO and Service Class

Find the DAO and services classes.
IPersonDAO.java
package com.concretepage.dao;
import java.util.List;
import com.concretepage.entity.Person;
public interface IPersonDAO {
    List<Person> getAllPersons();
    Person getPersonById(int pid);
    void addPerson(Person person);
    void updatePerson(Person person);
    void deletePerson(int pid);
    boolean personExists(String username);
} 
PersonDAO.java
package com.concretepage.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.concretepage.entity.Person;
@Transactional
@Repository
public class PersonDAO implements IPersonDAO {
	@Autowired
	private HibernateTemplate  hibernateTemplate;
	@Override
	public Person getPersonById(int pid) {
		return hibernateTemplate.get(Person.class, pid);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Person> getAllPersons() {
		String hql = "FROM Person as p ORDER BY p.pid";
		return (List<Person>) hibernateTemplate.find(hql);
	}	
	@Override
	public void addPerson(Person person) {
		hibernateTemplate.save(person);
	}
	@Override
	public void updatePerson(Person person) {
		Person p = getPersonById(person.getPid());
		p.setUsername(person.getUsername());
		p.setPassword(person.getPassword());
		p.setAge(person.getAge());
		p.setGender(person.getGender());
		p.setCity(person.getCity());
		hibernateTemplate.update(p);
	}
	@Override
	public void deletePerson(int pid) {
		hibernateTemplate.delete(getPersonById(pid));
	}
	@SuppressWarnings("unchecked")
	@Override
	public boolean personExists(String username) {
		String hql = "FROM Person as p WHERE p.username = ?";
		List<Person> persons = (List<Person>) hibernateTemplate.find(hql, username);
		return persons.size() > 0 ? true : false;
	}
} 
Person.java
package com.concretepage.entity;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
@Entity 
@Table(name= "person")
public class Person implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="pid")
        private int pid;	
	@Size(min=5, max=20)
	@Column(name = "username")
        private String username;
	@Size(min=8, max=15)
	@Column(name = "password")
        private String password;
	@Min(18)
	@Max(100)
	@Column(name = "age")
        private int age;
	@NotNull
	@Column(name = "gender")
        private String gender;
	@NotEmpty
	@Column(name = "city")
        private String city;
	public int getAge() {
		return age;
	}
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	private static Map<String, String> cityMap = new HashMap<String, String>(); 
	private static Map<String, String> genderOptions = new HashMap<String, String>();	
	public static Map<String, String> getPersonMap() {
		if (cityMap.size() == 0) {
			cityMap.put("Varanasi", "Varanasi");
			cityMap.put("Allahabad", "Allahabad");
			cityMap.put("Ghaziabad", "Ghaziabad");
			cityMap.put("Noida", "Noida");
		}
		return cityMap;
	}
	public static Map<String, String> getGenderOptions() {
               if(genderOptions.size() == 0) {
        	    genderOptions.put("M", "Male");
        	    genderOptions.put("F", "Female");
               }
               return genderOptions;
	}	
} 
IPersonService.java
package com.concretepage.service;
import java.util.List;
import com.concretepage.entity.Person;
public interface IPersonService {
     List<Person> getAllPersons();
     Person getPersonById(int pid);
     boolean addPerson(Person person);
     void updatePerson(Person person);
     void deletePerson(int pid);
} 
PersonService.java
package com.concretepage.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.concretepage.dao.IPersonDAO;
import com.concretepage.entity.Person;
@Service
public class PersonService implements IPersonService {
	@Autowired
	private IPersonDAO personDAO;
	@Override
	public Person getPersonById(int pid) {
		Person obj = personDAO.getPersonById(pid);
		return obj;
	}	
	@Override
	public List<Person> getAllPersons(){
		return personDAO.getAllPersons();
	}
	@Override
	public synchronized boolean addPerson(Person person){
             if (personDAO.personExists(person.getUsername())) {
    	         return false;
             } else {
    	         personDAO.addPerson(person);
    	         return true;
             }   
	}
	@Override
	public void updatePerson(Person person) {
		personDAO.updatePerson(person);
	}
	@Override
	public void deletePerson(int pid) {
		personDAO.deletePerson(pid);
	}
} 

Create Controller and View

Find the controller class
PersonController.java
package com.concretepage.controller;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import com.concretepage.entity.Person;
import com.concretepage.service.IPersonService;
@Controller
public class PersonController {
	@Autowired
	private IPersonService personService;
	@Autowired
	private MessageSource messageSource;
	@Autowired
	private LocaleResolver localeResolver;
	@RequestMapping(value="personform")
	public ModelAndView user(){
		ModelAndView mv = new ModelAndView("personform","person",new Person());
		setPageData(mv.getModelMap());
		return mv;
	}
	@RequestMapping(value="addPerson", method = RequestMethod.POST)
	public String addPerson(@ModelAttribute("person") @Valid Person person, BindingResult result, 
			ModelMap model, HttpServletRequest request) {
	    if(!result.hasErrors()) {
	    	boolean flag = personService.addPerson(person);
	    	if (flag) {
				model.addAttribute(new Person());
				model.addAttribute("msg", getMsg("person.added", request));
	    	} else {
	    		        model.addAttribute("msg", getMsg("person.duplicate", request));
	    	}
	    }
	    setPageData(model);
	    return "personform";
	}
	@RequestMapping(value="personById")
	public String getPersonById(ModelMap model, HttpServletRequest request) {
		int pid = Integer.parseInt(request.getParameter("pid"));
		Person person = personService.getPersonById(pid);
		setPageData(model);
		model.addAttribute(person);		
		return "personform";
	}
	@RequestMapping(value="updatePerson", method = RequestMethod.POST)
	public String updatePerson(@ModelAttribute("person") @Valid Person person, BindingResult result,
			ModelMap model, HttpServletRequest request) {
		if(!result.hasErrors()) {
			personService.updatePerson(person);
			model.addAttribute(new Person());
			model.addAttribute("msg", getMsg("person.updated", request));
		}
		setPageData(model);
		return "personform";
	}	
	@RequestMapping(value="deletePerson")
	public String deletePerson(ModelMap model, HttpServletRequest request) {
		int pid = Integer.parseInt(request.getParameter("pid"));
		personService.deletePerson(pid);
		model.addAttribute(new Person());
		model.addAttribute("msg", getMsg("person.deleted", request));
		setPageData(model);
		return "personform";
	}
	private void setPageData(ModelMap model) {
		model.addAttribute("allData", personService.getAllPersons());
		model.addAttribute("genderOptions", Person.getGenderOptions());
		model.addAttribute("cityMap", Person.getPersonMap());	
	}
	private String getMsg(String key, HttpServletRequest request) {
		return messageSource.getMessage(key, null, localeResolver.resolveLocale(request));
	}
}	 

@Controller: Using this annotation, class becomes controller.
@Valid: The property annotated with this annotation is validated.
ModelMap: It is used for model data for UI as java Map.
BindingResult : It provides validation error object.

Now create view.
personform.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en-US">
<head><title>Spring 4 MVC + Hibernate</title>
</head>
<body>
  <form:form  id="myform" action="addPerson" method="POST" commandName="person">
           <h3>
                    <c:if test="${person.pid==0}">
		       Add New Person
	            </c:if>
	            <c:if test="${person.pid!=0}">
		      Update Person for Id: <c:out value="${person.pid}"/>
		      <form:hidden path="pid"/>
	            </c:if>
          </h3>
	  <table>
	    <tr> <td>User Name:</td> <td><form:input  path="username"/><form:errors path="username" cssClass="error-msg"/> </td> </tr>
	    <tr> <td>Password:</td> <td><form:password path="password"/><form:errors path="password" cssClass="error-msg"/> </td> </tr>
	    <tr> <td>Age: </td> <td><form:input path="age"/><form:errors path="age" cssClass="error-msg"/> </td> </tr>
	    <tr> <td>Gender: </td> 
	         <td> <form:radiobuttons path="gender" items="${genderOptions}"/>
	             <form:errors path="gender" cssClass="error-msg"/> </td> </tr>    
	    <tr> <td>City:</td> <td> 
	        <form:select path="city">
	           <form:option value="" label="--Select City--"/>
	           <form:options items="${cityMap}"/>
                </form:select>  
                <form:errors path="city" cssClass="error-msg"/>
	    </td> </tr>
	    <tr> <td colspan="2">
    	        <c:if test="${person.pid==0}">
			      <input type="button" value="Add" id="btn-add"> 
	         </c:if>
	         <c:if test="${person.pid!=0}">
			      <input type="button" value="Update" id="btn-update"> 
	         </c:if>
		</td> </tr>
		<tr> <td colspan="2" class="success-msg">
		   <c:out value="${msg}"/>
		</td> </tr>
	  </table>
	  <table>   
	      <tr>               <td> ID </td>
		                 <td> User Name </td>
				 <td> Age </td>
				 <td> Gender </td>
				 <td colspan="2"> City </td>
	      </tr>
    	      <c:forEach var="obj" items="${allData}">
		      <tr>
		                 <td> <c:out value="${obj.pid}"/> </td>
		                 <td> <c:out value="${obj.username}"/> </td>
				 <td> <c:out value="${obj.age}"/> </td>
				 <td> <c:out value="${obj.gender}"/> </td>
				 <td> <c:out value="${obj.city}"/> </td>
				 <td> <a href="${pageContext.request.contextPath}/deletePerson?pid=${obj.pid}">Delete </a> |
				     <a href="${pageContext.request.contextPath}/personById?pid=${obj.pid}">Edit</a> 
				 </td>
		      </tr>
	      </c:forEach>
          </table> 
  </form:form>
  <script src="${pageContext.request.contextPath}/app-resources/js/lib/jquery-2.2.3.min.js"></script>
  <script src="${pageContext.request.contextPath}/app-resources/js/myapp.js"></script>
  <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/app-resources/css/style.css"/>
</body>
</html> 

<form:form>: It create HTML form. commandName attribute specifies model class.
<form:input>: It creates HTML input field.
<form:password> : It creates HTML password field.
<form:radiobuttons> : It creates radio button.
<form:select> : It creates combo box.
<form:errors> : It prints HTML field validation error.

messages_en.properties
Size.person.username=User Name must be between 5 to 20 characters
Size.person.password=Password must be between 8 to 15 characters
Min.person.age= Minimum age must be 18 years.
Max.person.age= Maximum age must be 100 years.
NotNull.person.gender=Gender must be selected.
NotEmpty.person.city= City must be selected. 

person.added = Person added successfully.
person.duplicate = User name already exits.
person.updated = Person updated successfully.
person.deleted = Person deleted successfully. 

myapp.js
$("#btn-add").click(function() {
          $("#myform").attr("action", "addPerson");
          $("#myform").submit();
});

$("#btn-update").click(function() {
	  $("#myform").attr("action", "updatePerson");
	  $("#myform").submit();
}); 

style.css
.error-msg {
	color: red;
}
.success-msg {
	color: green;
} 

Spring MVC Hibernate Integration using XML

Here we will provide Spring MVC hibernate integration using XML. Spring MVC and hibernate configurations are being performed in XML.

XML based Project Structure in Eclipse

Find the print screen of XML based project structure in eclipse.
Spring 4 MVC + Hibernate 4 + MySQL + Maven CRUD Integration using Annotation and XML with Tomcat 8 and Spring Boot Example

XML based Hibernate Configuration

Find the hibernate configuration using XML.
db-config.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:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

	<context:property-placeholder location="classpath:database.properties"/> 
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" >
		<property name="driverClassName" value="${database.driver}" />
		<property name="url" value="${database.url}" />
		<property name="username" value="${database.root}" />
		<property name="password" value="${database.password}" />
	</bean>
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
	    <property name="dataSource" ref="dataSource"/>
	    <property name="hibernateProperties">
			<props>
			   <prop key="hibernate.dialect">${hibernate.dialect}</prop>
			   <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
			   <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
			</props>
	    </property>
            <property name="packagesToScan" value="com.concretepage.entity"></property> 
	</bean>
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
	    <property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
		<constructor-arg name="sessionFactory" ref="sessionFactory"/>  
	</bean>	
	<tx:annotation-driven transaction-manager="transactionManager" /> 		
</beans> 

<context:property-placeholder> : It is the replacement of PropertySourcesPlaceholderConfigurer that uses ${...} to externalize property value.
<tx:annotation-driven> : It enables annotation based transaction management.

Spring MVC Application Context XML Configuration

Find spring MVC configuration using XML.
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">            

   <context:component-scan base-package="com.concretepage"/>
   <mvc:annotation-driven />
   <mvc:resources mapping="/app-resources/**" location="/resources/"/>
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	  <property name="prefix" value="/WEB-INF/view/"/>
	  <property name="suffix" value=".jsp"/> 
   </bean>
   <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
	  <property name="basename" value="/WEB-INF/i18/messages" />
	  <property name="defaultEncoding" value="UTF-8" />
   </bean>   
   <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
	  <property name="defaultLocale" value="en" />
	  <property name="cookieName" value="myLocaleCookie" />
	  <property name="cookieMaxAge" value="4800" />
   </bean>
   <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="mylocale" />
   </bean>     
   <import resource="db-config.xml"/>
</beans> 

<context:component-scan>: It scans the annotated component in the given classpath specified in base-package.
<mvc:annotation-driven> : It enables annotation based spring MVC controller.
<mvc:resources> : It is used to serve static resources. We need to define mapping for actual resource path.

Create web.xml

Create web.xml.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

        <display-name>Spring 4 MVC Example</display-name> 
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app> 

Run Application

To run the example find below steps.
1. Create database using MySQL.
2. Download source code.
3. Navigate to root directory using command prompt and run maven command as mvn clean package.
4. Install war file in Tomcat 8
5. Run the URL http://localhost:8080/spring-mvc/personform

If we submit the form without filling it, we will get validation errors.
Spring 4 MVC + Hibernate 4 + MySQL + Maven CRUD Integration using Annotation and XML with Tomcat 8
To add the person, fill the data and then click on Add button.
Spring 4 MVC + Hibernate 4 + MySQL + Maven CRUD Integration using Annotation and XML with Tomcat 8
To update a person, first click on Edit and do changes and then click on Update button.
Spring 4 MVC + Hibernate 4 + MySQL + Maven CRUD Integration using Annotation and XML with Tomcat 8
To delete a person, click on Delete button.
Spring 4 MVC + Hibernate 4 + MySQL + Maven CRUD Integration using Annotation and XML with Tomcat 8


Now I am done. Happy spring MVC learning!

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us