Hibernate integration in Struts2

The Hibernate is most popular ORM (Object Relational Mapping) framework in the market. You can integrate it in all Java/J2EE based framework. You can develop with xml configuration or with annotations.

Let's demonstrate how to integrate Hibernate in Struts2 framework without plug-in.
In this example I am creating CRUD application in Struts 2 with hibernate framework. 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 - "Struts2Hibernate1".

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
asm-3.3.jar
asm-tree-3.3.jar
cglib-2.2.jar
commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-lang3-3.1.jar
commons-logging-1.1.jar
dom4j-1.6.1.jar
freemarker-2.3.19.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate-testing.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
mysql-connector-java-5.1.7-bin.jar
ognl-3.0.6.jar
slf4j-api-1.6.1.jar
struts2-core-2.3.12.jar
xwork-core-2.3.12.jar

Step 4: Create a View page index.jsp :
<%taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Hibernate in Struts2</title>
</head>
<body>
<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;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
public class EmpAction extends ActionSupport implements 
  ModelDriven<Employee>,Preparable {
  Employee emp;
  private String message;
  List<Employee> emps;
  @Override
  public Employee getModel() {
    return emp;
  }

  public String getMessage() {
    return message;
  }

  public List<Employee> getEmps() {
    return emps;
  }

  @Override
  public void prepare() throws Exception {
    emp = new Employee();
    message = "";
    emps = new ArrayList<Employee>();
  }

  // save method
  public String save() {
    // message = "Add method executed";
    message = new EmpDao().addEmp(emp);
    System.out.println("save" + message);
    return SUCCESS;
  }

  // delete method
  public String delete() {
    // message = "delete method executed";
    message = new EmpDao().deleteEmp(emp);
    System.out.println(message);
    return SUCCESS;
  }

  // update method
  public String update() {
    // message = "update method executed";
    message = new EmpDao().updateEmp(emp);
    return SUCCESS;
  }

  // query method
  public String query() {
    message = "query method executed";
    Employee emp2 = new EmpDao().queryEmp(emp);
    emps.add(emp2);
    return SUCCESS;
  }

  // showall method
  public String showall() {
    message = "All Employees";
    emps = new EmpDao().showallEmp();
    return SUCCESS;
  }

}

Step 6: Create POJO class Employee.java:
package techmyguru.actions;
public class Employee {
  private String eid;
  private String name;
  private String city;
  private double salary;
  public Employee() {  }
  public Employee(String eid, String name, String city, double 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 DAO class EmpDao.java :
package techmyguru.actions;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class EmpDao {
private SessionFactory sessionfactory;
private Session session;

public EmpDao() {
if (sessionfactory == null)
  sessionfactory = new Configuration().configure()
        .buildSessionFactory();
  session=sessionfactory.openSession();
}
public String addEmp(Employee emp)
{
  session.beginTransaction().begin();
  session.save(emp);
  session.beginTransaction().commit();
  return "Employee record Inserted";
}
public String updateEmp(Employee emp)
{
  String status="Not updated";
  session.beginTransaction().begin();
  Employee emp1=(Employee)session.get(Employee.class, emp.getEid());
  if(emp1!=null)
  {
    emp1.setName(emp.getName());
    emp1.setCity(emp.getCity());
    emp1.setSalary(emp.getSalary());
    session.update(emp1);
    status="Employe updated";
  }
  session.beginTransaction().commit();
  return status;
}
public String deleteEmp(Employee emp)
{
  String status="Not deleted";
  session.beginTransaction().begin();
  Employee emp1=(Employee)session.get(Employee.class, emp.getEid());
  if(emp1!=null)
  {
    session.delete(emp1);
    status="Employe Deleted";
  }
  session.beginTransaction().commit();
  return status;
}
public Employee queryEmp(Employee emp)
{
  Employee emp1=(Employee)session.get(Employee.class, emp.getEid());
  return emp1;
}
public List<Employee> showallEmp()
{
  Query qr = session.createQuery("from Employee");
  List<Employee> emps=qr.list();
  return emps;
}
}

Step 8: 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 9: Create hibernate.cfg 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 10: 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>
<package name="default" extends="struts-default">
  <action name="*EmpAction" class="techmyguru.actions.EmpAction"  method="{1}">
  <result name="success">index.jsp</result>
  </action>
  </package>
</struts>  

Step 11: Verify the project directory structure.
Hibernate integration with Struts2

Step 12: Run the project and get output.
Hibernate integration with Struts2

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

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

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

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

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

Previous Download Source Code Next

Comment by : Pradeep February 18th, 2016
Comment : Hi, its nice code to understand flow of execution thank you, suggestion is: it should delete or update user choice record

Comment by : kiran October 17th, 2015
Comment : thank u so much

Comment by : Singh May 4th, 2015
Comment : My query and showall buttons only displays the message but doesnot show the table values. what could be the issue

Comment by : Sushil kumar Bhaskar April 16th, 2015
Comment : One of the best ever seen for Struts2 Hibernate Integration Example Tutorial. Thanks buddy. Lifesaver www.skbh.in

Comment by : Vrushant Balikai February 23rd, 2015
Comment : thank you

Comment by : krishna November 3rd, 2014
Comment : please send me the code of the struts and hibernate integration application

Comment by : Abhishek Yadav October 30th, 2014
Comment : Thank you...so much...

Comment by : k k chandan June 6th, 2014
Comment : thanks

Comment by : manu October 27th, 2013
Comment : Hi, Nice Application.When i click on Show all button ,i am unable to get the records.Please help me and based on the id it's not working getting the 404 exception.If i enter all the values then it's

Comment by : manu October 27th, 2013
Comment : share the web.xml file

Comment by : Shankar Jaiswal September 26th, 2013
Comment : Its very good but i need the code.Can u give me the url of code. Thanks shankar


Write your Comment

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