Spring - Hibernate Integration

Reference - DZONE

In this tutorial, you will see how to integrate Spring and Hibernate. I assume you are comfortable with both. At the end of this example, you will learn to create a form through which you can add a user and list all the existing users, as shown below.
Here is the directory structure of the example.
 You need to have the following lib files in the WEB-INF/lib directory.
antlr-2.7.6
antlr-runtime-3.0
commons-collections-3.1
commons-dbcp
commons-logging-1.0.4
commons-pool
dom4j-1.6.1
ejb3-persistence
hibernate3
hibernate-annotations
hibernate-commons-annotations
hsqldb
javassist-3.4.GA
jstl
jta-1.1
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3
org.springframework.jdbc-3.0.0.M3
org.springframework.orm-3.0.0.M3
org.springframework.transaction-3.0.0.M3
org.springframework.web-3.0.0.M3
org.springframework.web.servlet-3.0.0.M3
slf4j-api-1.5.6
slf4j-simple-1.5.6
standard
The most important part of the example is the spring bean configuration. Here is the spring bean configuration file.
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.
    InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.
    annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.vaannila.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myUserDAO" class="com.vaannila.dao.UserDAOImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean name="/user/*.htm" class="com.vaannila.web.UserController" >
<property name="userDAO" ref="myUserDAO" />
</bean>
</beans>
Here, we use the Jakarta Commons DBCP BasicDataSource to set up a JDBC DataSource. I am using hsqldb database here. If you are using MySQL, then you need to change this configuration.
Hibernate SessionFactory can be configured in the spring bean configuration file itself, as shown above. You need not have a separate hibernate configuration file (hibernate.cfg.xml ) to do this. I am using Hibernate annotations in this example, so I am listing all the annotated classes using the annotatedClasses property. All the Hibernate-related configurations can be done using the hibernateProperties.
We use a separate DAO class to interact with the database. Using a setter injection, we inject the Hibernate SessionFactory.
We have a MultiActionController class to handle the web requests, so we use a wildcard character in the bean name ("/user/*.htm").
Here is the User class with the Hibernate annotations. If you want to add any database-related constraints, then you need to do it here.
package com.vaannila.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="USER")
public class User {
private Long id;
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
@Id
@GeneratedValue
@Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="USER_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="USER_PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name="USER_GENDER")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Column(name="USER_COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="USER_ABOUT_YOU")
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
@Column(name="USER_COMMUNITY")
public String[] getCommunity() {
return cohttp://www.dzone.com/node/add/articlemmunity;
}
public void setCommunity(String[] community) {
this.community = community;
}
@Column(name="USER_MAILING_LIST")
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
Our DAO class implements the UserDAO interface, and here, we have just two methods: one to save the user details and the other to list all the users.
package com.vaannila.dao;
import java.util.List;
import com.vaannila.domain.User;
public interface UserDAO {
public void saveUser(User user) ;
public List<User> listUser() ;
}
In the DAO class, we use Hibernate Template to access the database. To create a Hibernate Template instance, you need a Session Factory. For this purpose, we injected the sessionFactory property in the Spring bean configuration file.
package com.vaannila.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.vaannila.domain.User;
public class UserDAOImpl implements UserDAO {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) 
    {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
@Override
public void saveUser(User user) {
hibernateTemplate.saveOrUpdate(user);
}
Hibernate Template is thread-safe and reusable. You need not manually open and close Session; Hibernate Template will do that for you.
The UserController class extends MultiActionController class. The UserDAOImpl instance is injected using a setter injection. In the add method, we call the saveUser() method and redirect the control to the "list.htm" url. This will invoke the list() method. In the list method, you add two things to the modelMap: the user list to display the list of users and an instance of the user object to bind the form fields in the userForm.jsppage.
package com.vaannila.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction. MultiActionController;
import com.vaannila.dao.UserDAO;
import com.vaannila.domain.User;
public class UserController extends MultiActionController {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
userDAO.saveUser(user);
return new ModelAndView("redirect:list.htm");
}
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("userList", userDAO.listUser());
modelMap.addAttribute("user", new User());
return new ModelAndView("userForm", modelMap);
}
}
 In the jsp page, we use Spring Form tags to display the form fields and jstl tags to display the list of users.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style type="text/css">
.even {
background-color: silver;
}
</style>
<title>Registration Page</title>
</head>
<body>
<form:form action="add.htm" commandName="user">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" /> 
            <form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="India" label="India" />
<form:option value="USA" label="USA" />
<form:option value="UK" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><form:checkbox path="community" value="Spring" label="Spring" />
                <form:checkbox path="community" value="Hibernate" label="Hibernate" />
                <form:checkbox path="community" value="Struts" label="Struts" /></td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
</form:form>
<c:if test="${fn:length(userList) > 0}">
<table cellpadding="5">
<tr class="even">
<th>Name</th>
<th>Gender</th>
<th>Country</th>
<th>About You</th>
</tr>
<c:forEach items="${userList}" var="user" varStatus="status">
<tr class="<c:if test="${status.count % 2 == 0}">even</c:if>">
<td>${user.name}</td>
<td>${user.gender}</td>
<td>${user.country}</td>
<td>${user.aboutYou}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
 Now you can execute the example by running the redirect.jsp page. You will see the following page.
After entering a few records, you will see the user's list displayed below.

Post a Comment

0 Comments