In this tutorial
you will see how to integrate spring and hibernate. I assume you are
comfortable with both spring and hibernate. 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-6
antlr-runtime-0
commons-collections-1
commons-dbcp
commons-logging-4
commons-pool
dom4j-1
ejb3-persistence
hibernate3
hibernate-annotations
hibernate-commons-annotations
hsqldb
javassist-GA
jstl
jta-1
org.springframework.asm-M3
org.springframework.beans-M3
org.springframework.context-M3
org.springframework.context.support-M3
org.springframework.core-M3
org.springframework.expression-M3
org.springframework.jdbc-M3
org.springframework.orm-M3
org.springframework.transaction-M3
org.springframework.web-M3
org.springframework.web.servlet-M3
slf4j-api-6
slf4j-simple-6
standard
The most
important part of the example is the spring bean configuration. Here is the
spring bean configuration file.
<?xml version="0" encoding="UTF-8"?>
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://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="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate
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 setup 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 seperate 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 theannotatedClasses property. All the hibernate related
configurations can be done using thehibernateProperties.
We use a seperate
DAO class to interact with the database. Using setter injection we inject the
Hibernate SessionFactory.
We have a MultiActionController class to handle the web requests, so we use wildcard charcter 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;
}
7
7@Column(name="USER_COMMUNITY")
7public String[]
getCommunity() {
7return cohttp://www.dzone.com/node/add/articlemmunity;
7}
7public void setCommunity(String[] community) {
7this.community =
community;
7}
7
8@Column(name="USER_MAILING_LIST")
8public Boolean
getMailingList() {
8return mailingList;
8}
8public void setMailingList(Boolean mailingList) {
8this.mailingList =
mailingList;
8}
8
8}
Our DAO class
implements the UserDAO interface, here we have just two methods one to save the
user details and 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.hibernateHibernateTemplate;
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 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 theuserForm.jsp page.
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">
7<tr class="<c:if test="${status.count % 2 == 0}">even</c:if>">
7<td>${user.name}</td>
7<td>${user.gender}</td>
7<td>${user.country}</td>
7<td>${user.aboutYou}</td>
7</tr>
7</c:forEach>
7</table>
7</c:if>
8</body>
8</html>
Now you can execute the example
by running the redirect.jsp page. You will see the following page.
Aftering entering
few records you will see the user's list dispalyed below.

No comments:
Post a Comment