Meyyappan has posted 101 posts at DZone. View Full User Profile

Struts 2 Hibernate Integration Tutorial

06.15.2012
| 48785 views |
  • submit to reddit

In this example you will see how to integrate Struts 2 and Hibernate using the "Full Hibernate Plugin 1.4 GA" ( Full Hibernate Plugin 1.4 GA ).

You will see how to add a user using the user registration form shown below and to list all the existing users.

To use the Full Hibernate Plugin 1.4 GA you need to add the following lib files to the lib directory.

antlr-2.7.6.jar
commons-collections-3.1.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.3.jar
commons-logging-1.1.jar
dom4j-1.6.1.jar
ejb3-persistence.jar
freemarker-2.3.13.jar
hibernate3.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
hibernate-validator.jar
hsqldb.jar
javassist-3.9.0.GA.jar 
jta-1.1.jar
junit-3.8.1.jar
log4j-1.2.15.jar
ognl-2.6.11.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.8.jar
struts2-convention-plugin-2.1.6.jar
struts2-core-2.1.6.jar
struts2-fullhibernatecore-plugin-1.4-GA.jar
xwork-2.1.2.jar
The directory structure of the example is shown below.



The session object and transaction object will be injected using the @SessionTarget and @TransactionTarget annotation respectively.

package com.vaannila.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.vaannila.domain.User;

public class UserDAOImpl implements UserDAO {

	@SessionTarget
	Session session;
    
	@TransactionTarget
	Transaction transaction;

	@SuppressWarnings("unchecked")
	@Override
	public List<User> listUser() {	
		List<User> courses = null;
		try {
			courses = session.createQuery("from User").list();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return courses;
	}

	@Override
	public void saveUser(User user) {
		try {
			session.save(user);
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		} 
	}

}

For the session and transaction injection to happen throught the plug-in the org.hibernate. Session and org.hibernate.Transaction objects should be declared as class variables and not at method level. You can keep these variables in a generic DAO class and extend all the other DAO's from it. When using this plug-in there is no need to explicitly commit the transaction and close the session, both will be done automatically.

The "transaction.rollback()" should be used only in the methods that updates the database.

In the hibernate configuration file, we configure it to work with the hsqldb database.

<?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"> org.hsqldb.jdbcDriver </property>
		<property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost </property>
		<property name="hibernate.connection.username">sa</property>
		<property name="connection.password"></property>
		<property name="connection.pool_size">1</property>
		<property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect </property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">create</property>
		<mapping class="com.vaannila.domain.User" />
	</session-factory>
</hibernate-configuration>

The domain object User class is shown below.

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 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_MAILING_LIST")
	public Boolean getMailingList() {
		return mailingList;
	}
	public void setMailingList(Boolean mailingList) {
		this.mailingList = mailingList;
	}

}

In the UserAction class we have two methods add() and list() to add and list all users respectively.

package com.vaannila.web;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.vaannila.dao.UserDAO;
import com.vaannila.dao.UserDAOImpl;
import com.vaannila.domain.User;

public class UserAction extends ActionSupport implements ModelDriven<User> {

	private static final long serialVersionUID = -6659925652584240539L;

	private User user = new User();
	private List<User> userList = new ArrayList<User>();
	private UserDAO userDAO = new UserDAOImpl();
	
	@Override
	public User getModel() {
		return user;
	}
	
	public String add()
	{
		userDAO.saveUser(user);
		return SUCCESS;
	}
	
	public String list()
	{
		userList = userDAO.listUser();
		return SUCCESS;
	}
		
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

}

For the session and transaction injection to happen through the plug-in, the UserDAO should be a class level declaration and should not be declared at method level.

To use this plug-in you need to extend the package from hibernate-default package. To configure this you can either use XML or annotations, I am using XML.

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="default" extends="hibernate-default">
		<action name="addUser" method="add" class="com.vaannila.web.UserAction">
			<result name="success" type="redirect">listUser</result>
		</action>
		<action name="listUser" method="list" class="com.vaannila.web.UserAction">
			<result name="success">/register.jsp</result>
		</action>
	</package>
</struts>

The register.jsp page is shown below.

<%@ 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">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
@import url(style.css);
</style>
</head>
<body>
<s:form action="addUser">
	<s:textfield name="name" label="User Name" />
	<s:password name="password" label="Password" />
	<s:radio name="gender" label="Gender" list="{'Male','Female'}" />
	<s:select name="country" list="{'India','USA','UK'}" headerKey=""
		headerValue="Country" label="Select a country" />
	<s:textarea name="aboutYou" label="About You" />
	<s:checkbox name="mailingList"
		label="Would you like to join our mailing list?" />
	<s:submit />
</s:form>

<s:if test="userList.size() > 0">
	<div class="content">
	<table class="userTable" cellpadding="5px">
		<tr class="even">
			<th>Name</th>
			<th>Gender</th>
			<th>Country</th>
			<th>About You</th>
			<th>Mailing List</th>
		</tr>
		<s:iterator value="userList" status="userStatus">
			<tr
				class="<s:if test="#userStatus.odd == true ">odd</s:if><s:else>even</s:else>">
				<td><s:property value="name" /></td>
				<td><s:property value="gender" /></td>
				<td><s:property value="country" /></td>
				<td><s:property value="aboutYou" /></td>
				<td><s:property value="mailingList" /></td>
			</tr>
		</s:iterator>
	</table>
	</div>
</s:if>
</body>
</html>

You can download and try the Struts 2 Hibernate Integration Example here.

Source :Download (15 KB)
Source + Lib :Download (9.8 MB
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: