Search

Struts 2 Hibernate Integration example

In this example you will see how to integrate Struts 2 and Hibernate using the "Full Hibernate Plugin 4 GA" ( Full Hibernate Plugin 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 4 GA you need to add the following lib files to the lib directory.
antlr-jar
commons-collections-jar
commons-fileupload-jar
commons-io-jar
commons-lang-jar
commons-logging-jar
dom4j-jar
ejb3-persistence.jar
freemarker-jar
hibernatejar
hibernate-annotations.jar
hibernate-commons-annotations.jar
hibernate-validator.jar
hsqldb.jar
javassist-GA.jar
jta-jar
junit-jar
log4j-jar
ognl-jar
slf4j-api-jar
slf4j-log4j12-jar
struts2-convention-plugin-jar
struts2-core-jar
struts2-fullhibernatecore-plugin-4-GA.jar
xwork-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.strutsplugin.annotations.SessionTarget;
importcom.googlecode.s2hibernate.strutsplugin.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 andorg.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="0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 0//EN"
<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;
}

7@Column(name="USER_MAILING_LIST")
7public Boolean getMailingList() {
7return mailingList;
7}
7public void setMailingList(Boolean mailingList) {
7this.mailingList = mailingList;
7}
7 
7}
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.xworkActionSupport;
import com.opensymphony.xworkModelDriven;
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 0//EN"

<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 01 Transitional//EN" "http://www.worg/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>

No comments:

Post a Comment