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
<properties>
<spring.version>3.1.0.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.15</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>
</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.
User.java
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;
@Entity
@Table(name = "User")
public class User{
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer Id;
@Column(name="username")
private String username;
@Column(name="password")
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.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <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" /> </session-factory> </hibernate-configuration>
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
LoginController.java
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(){
setCommandClass(Login.class);
setCommandName("loginForm");
}
@Override
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{
@Override
public boolean supports(Class<?> clazz) {
return Login.class.isAssignableFrom(clazz);
}
@Override
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.
messages.properties
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.
loginForm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="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"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Page</title> </head> <body> <form:form method="POST" commandName="loginForm"> <table> <tr> <td></td> <td></td> <td><form:errors/></td> </tr> <tr> <td>Email :</td> <td><form:input path="email" /></td> <td><form:errors path="email" cssClass="error" /></td> </tr> <tr> <td>Password :</td> <td><form:password path="password" /></td> <td><form:errors path="password" cssClass="error" /></td> </tr> </table> <tr> <td colspan="3"><input type="submit" value="Login"></td> </tr> </form:form> </body> </html>
On successful submission of loginform, loginSuccess.jsp page will be displayed.
<%@ 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>Login Successful</title>
</head>
<body>
${login.email} successfully logged in<br/>
</body>
</html>
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" /> </property> </bean>
Also add the properties file.
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages" />

can i have the source code
thanq so much….
Hi,
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.
Dear Akram, please follow the steps from Figure 2.4 in following link.
http://kruders.com/maven/enable-maven-for-dynamic-web-projects-in-eclipse/
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.
thanks.
Eclipse – > File – > Import – > Existing Projects into Workspace
Then follow the steps from Figure 2.4 in following link.
http://kruders.com/maven/enable-maven-for-dynamic-web-projects-in-eclipse/
Thanks lot. I will try it.
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.