Spring + Hibernate + MySql + Maven Example

In this tutorial, I will show you how to integrate Hibernate with Spring 3.

Tools and technologies used :

  • Hibernate
  • Spring
  • MySql
  • Maven
  • Eclipse

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml



	<!-- Spring 3 dependencies -->




1. Sql Script

Use the following Sql Script for creating table.

create table User(
    ID int(10) primary key NOT NULL AUTO_INCREMENT,
    username varchar(50),
    password varchar(50));

2. Pojo

Now create User class that maps java class to User table.


package com.kruders.model.bean;

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

@Table(name = "User")
public class User{
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Integer Id;
    private String username;
    private String password;
	public Integer getId() {
		return Id;
	public void setId(Integer id) {
		Id = id;
	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;

3. Hibernate Configuration File

Now create the hibernate configuration file and add all the mapping files.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
	<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">password</property>
	<property name="connection.pool_size">1</property>
	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
	<property name="show_sql">true</property>
	<mapping class="com.kruders.model.bean.User" />

4. Hibernate Utility Class

Now create HibernateUtil class. The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.

package com.kruders.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
    public static SessionFactory getSessionFactory() {
        return sessionFactory;

5. Model

Following is the Login class.

package com.kruders.domain;
public class Login {
    String email;
    String password;
    public String getEmail() {
        return email;
    public void setEmail(String email) {
        this.email = email;
    public String getPassword() {
        return password;
    public void setPassword(String password) {
        this.password = password;

6. Controller

In order to handle spring forms, you need your controller to extend SimpleFormController. Following class shows you how to extend SimpleFormController


package com.kruders.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.kruders.domain.Login;
public class LoginController extends SimpleFormController{
    public LoginController(){
    protected ModelAndView onSubmit(Object command) throws Exception {
        Login login = (Login) command;
        return new ModelAndView("loginSuccess","login",login);

Extending SimpleFormController makes the controller to handle form requests. Here in LoginController contructor, controller will bind values to/from Spring’s form tags.

public LoginController(){
    setCommandClass(Login.class);  //Spring form values gets stored into Login object
    setCommandName("loginForm");    //if loginForm is submitted, Spring will forward request to this Controller

When loginForm is submitted, onsubmit() method will be executed to handle form’s request and return ModelAndView on success. All the forms field values will be submitted as Strings to the form controller.

7. Form Validation

To validate the form fields we have a seperate LoginValidator class that implements the Validator interface, override the validate() method perform all the validations.

Following in the LoginValidator class.

package com.kruders.validator;

import java.util.List;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.kruders.domain.Login;
import com.kruders.model.bean.User;
import com.kruders.util.HibernateUtil;

import org.hibernate.Session;

public class LoginValidator implements Validator{
	public boolean supports(Class<?> clazz) {
		return Login.class.isAssignableFrom(clazz);

	public void validate(Object target, Errors errors) {
		Login loginuser = (Login) target;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
		Session session = HibernateUtil.getSessionFactory().openSession();
        List<User> userList = session.createQuery("from User where username ='" + loginuser.getEmail() + "' and password ='" + loginuser.getPassword() + "'").list();
        if(userList.size() == 0) {
        	errors.reject("wrongcredential","Wrong Username or Password!!!");	

8. Properties File

A properties file to store all the error messages. Here we have the error messages in a seperate properties file so we add the error code, you can even add the error messages directly.


email.required = User Name is required
password.required = Password is required

9. View

Following is the form login form that contains Spring’s Form Tags and display error message if any.

form:errors tag to display errors in jsp files.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
<form:form method="POST" commandName="loginForm">
			<td>Email :</td>
			<td><form:input path="email" /></td>
			<td><form:errors path="email" cssClass="error" /></td>
			<td>Password :</td>
			<td><form:password path="password" /></td>
			<td><form:errors path="password" cssClass="error" /></td>
			<td colspan="3"><input type="submit" value="Login"></td>

On successful submission of loginform, loginSuccess.jsp page will be displayed.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Successful</title>
${login.email} successfully logged in<br/>

10. Spring Bean Configuration

We now declare the controller and validator for the loginform Spring Bean Configuration file.

<bean class="com.kruders.controller.LoginController">
    <property name="formView" value="loginForm" />
    <property name="successView" value="loginSuccess" />
    <!-- Map a validator -->
    <property name="validator">
        <bean class="com.kruders.validator.LoginValidator" />

Also add the properties file.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages" />
You can download the source code of this example here.

, , ,

12 Responses to Spring + Hibernate + MySql + Maven Example

  1. linuxbot March 6, 2013 at 5:18 pm #

    can i have the source code

    • linuxbot March 7, 2013 at 7:25 am #

      thanq so much….

  2. Aatif March 11, 2013 at 12:11 pm #

    Hi.. There’s an issue i’m facing while running your code. There was an error i found in LoginController class regarding package import. I added servlet.2.5.jar to remove this error. Now no error in project but it’s not running. Here is the following stacktrace.

    INFO: Starting Servlet Engine: Apache Tomcat/7.0.25
    Mar 11, 2013 5:35:56 PM org.apache.catalina.loader.WebappClassLoader validateJarFile
    INFO: validateJarFile(E:\Utsav\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Spring_Hibernate\WEB-INF\lib\servlet-api-2.5.jar) – jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
    Mar 11, 2013 5:35:56 PM org.apache.catalina.startup.ContextConfig webConfig
    SEVERE: Unable to determine URL for WEB-INF/classes
    javax.naming.NameNotFoundException: Resource /WEB-INF/classes not found
    at org.apache.naming.resources.BaseDirContext.listBindings(BaseDirContext.java:733)
    at org.apache.naming.resources.ProxyDirContext.listBindings(ProxyDirContext.java:546)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1197)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:825)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:300)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1568)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1558)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Mar 11, 2013 5:35:58 PM org.apache.catalina.core.ApplicationContext log
    INFO: No Spring WebApplicationInitializer types detected on classpath
    Mar 11, 2013 5:35:58 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-bio-8080"]
    Mar 11, 2013 5:35:58 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-8009"]
    Mar 11, 2013 5:35:58 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 1800 ms


  3. Akram April 5, 2013 at 4:00 pm #


    I imported your code to eclipse, when run it, I got :

    HTTP Status 404 – /Spring_Hibernate/


    type Status report

    message /Spring_Hibernate/

    description The requested resource is not available.


    Apache Tomcat/7.0.37

    Your help is appreciated.

  4. Akram April 5, 2013 at 7:11 pm #

    Thanks for your quick response,
    Did you mean to create a new project and then copy your code to it, instead of going to Eclipse –> File –> Import –> Maven existing project ?

    I just Imported your maven project, when I :

    select Deployment Assembly, I got :
    The given project is not a virtual component project.


  5. naga May 8, 2013 at 6:11 am #

    Hi, can you please provide the details of test cases. I did maven build and copied war under tomcat–>webapps. how can i start the application. can you please provide step by step. Thanks in advance.

  6. ravi May 29, 2013 at 6:27 am #

    Can you please update and provide this example with annotations.
    very good example for the beginners..

  7. Iaroslaw Kardash October 24, 2013 at 4:04 am #

    thanks for so comprehenced example.
    i have some question (cause I’m at the beginning level of web development) concerning what folder in the project should be located hibernate.cfg.xml file in? Under src?
    would be helpful for your answer on such a simple question

  8. jodha November 27, 2014 at 5:03 am #

    can u please provide the output screenshots. so that make it easier.

Leave a Reply