Hibernate in Struts2 with hibernate-plug-in

In the previous section, I have discussed how to use hibernate framework in Struts 2 framework. You can use hibernate plug-in for the same. You can inject Session and Transaction in DAO class and it can be configured using annotations, xml and both.
Find plug-in references -
Let's demonstrate how to integrate Hibernate plug-in in Struts2 framework.
In this example I am creating CRUD application in Struts 2 with hibernate framework and plug-in. The mapping is based on XML file. I have create two XML configuration file - src\hibernate.cgf.xml (Which contains database configuration information and URL of hbm.xml file) and Employee.hbm.xml (It is mapping file between POJO class - Employee.java and table - Employee).

The following software are used in this example :
Database connection information
  • Driver class - com.mysql.jdbc.Driver
  • Database URL - jdbc:mysql://localhost:3306/test
  • User - root
  • password - root
  • Database name - test
The employee table will create at runtime

Follow the following steps to create this project :

Step 1: Create a Dynamic Web Project in eclipse - "Struts2Hibernate2".

Step 2: Edit deployment descriptor web.xml. [ Click here If you are not familiar with Struts2 application environment setup in Eclipse. ]

Step 3: The following Struts2 and hibernate jar files required in WEB-INF\lib folder in your project.
antlr-2.7.2.jar
antlr-2.7.6.jar
aopalliance-1.0.jar
asm-attrs.jar
asm.jar
c3p0-0.9.1.jar
cglib-2.1.3.jar
classworlds-1.1.jar
commons-beanutils-1.7.0.jar
commons-chain-1.2.jar
commons-collections-3.2.jar
commons-digester-1.8.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
commons-logging-api-1.1.jar
commons-validator-1.3.1.jar
concurrent-1.3.2.jar
connector.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
ejb3-persistence.jar
ezmorph-1.0.3.jar
freemarker-2.3.13.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
hibernate-entitymanager.jar
hibernate-validator.jar
hibernate3.jar
jaas.jar
jacc-1_0-fr.jar
javassist.jar
jaxen-1.1-beta-7.jar
jboss-archive-browsing.jar
jboss-cache.jar
jboss-common.jar
jboss-jmx.jar
jboss-system.jar
jdbc2_0-stdext.jar
jgroups-2.2.8.jar
jta-1.1.jar
log4j-1.2.11.jar
mysql-connector-java-5.1.7-bin.jar
ognl-2.6.11.jar
oro-2.0.8.jar
oscache-2.1.jar
proxool-0.8.3.jar
struts2-convention-plugin-2.1.6.jar
struts2-core-2.1.6.jar
struts2-fullhibernatecore-plugin-2.2.2-GA.jar
swarmcache-1.0rc2.jar
xerces-2.6.2.jar
xml-apis.jar
xpp3_min-1.1.3.4.O.jar
xstream-1.2.2.jar
xwork-2.1.2.jar

Step 4: Create a View page index.jsp :
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Struts2 with Hibernate plugin</title>
<s:head/>
</head>
<body>
<s:actionmessage/>
<s:actionerror/>
<s:form action="EmpAction" method="post">
<s:textfield label="Enter Id" name="eid" value=""/>
<s:textfield label="Enter Name" name="name" value=""/>
<s:textfield label="Enter City" name="city" value=""/>
<s:textfield label="Enter Salary" name="salary" value="0"/>
<s:submit action="saveEmpAction" value="Save Emp"/>
<s:submit action="deleteEmpAction" value="Delete Emp"/>
<s:submit action="updateEmpAction" value="Update Emp"/>
<s:submit action="queryEmpAction" value="Query Emp"/>
<s:submit action="showallEmpAction" value="ShowAll"/>
</s:form>
<hr>
<s:property value="message"/>
<hr>
<table border="1">
<s:iterator value="emps">
<tr>
<td><s:property value="eid"/> </td>
<td><s:property value="name"/></td>
<td><s:property value="city"/></td>
<td><s:property value="salary"/></td>
</tr>
</s:iterator>
</body>
</html>

Step 5: Create action class EmpAction.java :
package techmyguru.actions;
// all import statements
public class EmpAction extends ActionSupport implements
ModelDriven<Employee>,Preparable {

Employee emp;

@SessionTarget
Session session;

@TransactionTarget
Transaction transaction;

private String message;

List<Employee> emps;

@Override
public Employee getModel() {
return emp;
}
// getter method for message and emps
@Override
public void prepare() throws Exception
{
emp = new Employee();
message = "";
emps = new ArrayList<Employee>();
}

public String validate1() {
String status="";
if(emp.getEid().length()==0)
{
addFieldError("eid","Id can be left blank");
status=INPUT;
}
if(emp.getName().length()==0)
{
addFieldError("name","Name can be left blank");
status=INPUT;
}
if(emp.getCity().length()==0)
{
addFieldError("city","City can be left blank");
status=INPUT;
}
if(emp.getSalary().length()==0)
{
addFieldError("salary","Salary can be left blank");
status=INPUT;
}
return status;
}

// save method
public String save() {
validate1();
String status = "";
try {
session.saveOrUpdate(emp);
emps.add(emp);
message = "Employee inserted";
status = SUCCESS;
} catch (Exception e) {
message = "Error in inserting record";
status = ERROR;
}
System.out.println("save" + message);
return status;
}

// delete method
public String delete() {
String status = "";
try {
Employee emp1=(Employee)session.get(Employee.class,emp.getEid());
if(emp1!=null)
{
session.delete(emp1);
emps.add(emp1);
message = "Employee deleted";
status = SUCCESS;
}
else
{
message = "Employee does not exists";
status = SUCCESS;
}
} catch (Exception e) {
message = "Error in fetching record";
status = ERROR;
}
System.out.println("query" + message);
return status;
}

// update method
public String update()
{
String status = "";
try {
Employee emp1=(Employee)session.get(Employee.class,emp.getEid());
if(emp1!=null)
{
emp1.setCity(emp.getCity());
double newSalary=Double.parseDouble(emp1.getSalary())
+Double.parseDouble(emp.getSalary());
emp1.setSalary(""+newSalary);
session.update(emp1);
emps.add(emp1);
message = "Employee updated";
status = SUCCESS;
}
else
{
message = "Employee does not exists";
status = SUCCESS;
}
} catch (Exception e)
{
message = "Error in updating record";
status = ERROR;
}
System.out.println("update" + message);
return status;
}

// query method
public String query()
{
String status = "";
try {
Employee emp1=(Employee)session.get(Employee.class,emp.getEid());
if(emp1!=null)
{
emps.add(emp1);
message = "Employee detail";
status = SUCCESS;
}
else
{
message = "Employee does not exists";
status = SUCCESS;
}
} catch (Exception e)
{
message = "Error in fetching record";
status = ERROR;
}
System.out.println("query" + message);
return status;
}

// showall method
public String showall()
{
String status = "";
try {
emps =session.createCriteria(Employee.class).list();
message = "Employee details";
status = SUCCESS;
} catch (Exception e)
{
message = "Error in fetching records";
status = ERROR;
}
System.out.println("showall" + message);
return status;
}
}

Step 6: Create POJO class Employee.java:
package techmyguru.actions;
public class Employee {
private String eid;
private String name;
private String city;
private String salary;

// default constructor
public Employee() {}

// parameterised constructor
public Employee(String eid, String name, String city, String salary) {
this.eid = eid;
this.name = name;
this.city = city;
this.salary = salary;
}
// all getter and setter methods
@Override
public String toString()
{
return eid + " " + name + " " + city + " " + salary;
}
}

Step 7: Create hibernate mapping file Employee.hbm.xml :
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="techmyguru.actions.Employee" table="EMPLOYEE">
<id name="eid" type="java.lang.String">
<column name="EID" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="city" type="java.lang.String">
<column name="CITY" />
</property>
<property name="salary" type="double">
<column name="SALARY" />
</property>
</class>
</hibernate-mapping>

Step 8: Create hibernate.cfg.xml file:
<?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.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="techmyguru/actions/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Step 9: Create struts configuration file src\struts.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.i18n.encoding" value="ISO-8859-1" />
<include file="struts-default.xml" />
<package name="default" extends="hibernate-default">
<default-interceptor-ref name="basicStackHibernate"/>

<action name="*EmpAction" class="techmyguru.actions.EmpAction"
method="{1}">
<interceptor-ref name="defaultStackHibernate"></interceptor-ref>
<result name="success">index.jsp</result>
<result name="input">index.jsp</result>
<result name="error">index.jsp</result>
</action>
</package>
</struts>

Step 10: Verify the project directory structure.
Hibernate plug-in integration with Struts2

Step 11: Run the project and get output.
Hibernate  plug-in  integration with Struts2

Fill the above form and click Save Emp button and get below response
Hibernate  plug-in integration with Struts2

Enter id and click Delete Emp button and get below response
Hibernate  plug-in integration with Struts2

Fill form and click Update Emp button and get below response
It will update record based on id
Hibernate  plug-in integration with Struts2

Enter id and click Query Emp button and get below response
Hibernate  plug-in integration with Struts2

Click Show All button and get below response
Hibernate  plug-in integration with Struts2

Previous Download Source Code Next


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code