In Struts2, there are no official plugins to integrate the Hibernate framework. But, you can workaround with the following steps :

  1. Register a custom ServletContextListener.
  2. In the ServletContextListener class, initialize the Hibernate session and store it into the servlet context.
  3. In action class, get the Hibernate session from the servlet context, and perform the Hibernate task as normal.

See the relationship :

Struts 2 <-- (Servlet Context) ---> Hibernate <-----> Database 

In this tutorial, it shows a simple customer module (add and list function), developed in Struts 2, and perform the database operation with Hibernate. The integration part is using the above stated mechanism (store and retrieve the Hibernate session in the servlet context).

This workaround is very similar with the classic Struts 1.x and Hibernate integration, just the classic Struts 1.x is using the Struts’s plugins; While the Struts 2 is using the generic servlet listener.

1. Project structure

See this full project folder structure.

Struts 2 Hibernate integration example

2. MySQL table script

Create a customer table for the demonstration. Here’s the SQL table script.

DROP TABLE IF EXISTS `mkyong`.`customer`;
CREATE TABLE  `mkyong`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,

3. Dependency

Get the Struts2, Hibernate and MySQL dependency libraries.

	<!-- Struts 2 -->

	<!-- MySQL database driver -->

	<!-- Hibernate core -->

	<!-- Hibernate core library dependency start -->



	<!-- Hibernate core library dependency end -->

	<!-- Hibernate query library dependency start -->
	<!-- Hibernate query library dependency end -->

4. Hibernate Stuffs

The Hibernate model and configuration stuffs. – Create a class for customer table.

package com.mkyong.customer.model;

import java.util.Date;

public class Customer implements {

	private Long customerId;
	private String name;
	private String address;
	private Date createdDate;

	//getter and setter methods

Customer.hbm.xml – Hibernate mapping file for customer.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    <class name="com.mkyong.customer.model.Customer" 
	table="customer" catalog="mkyong">

        <id name="customerId" type="java.lang.Long">
            <column name="CUSTOMER_ID" />
            <generator class="identity" />
        <property name="name" type="string">
            <column name="NAME" length="45" not-null="true" />
        <property name="address" type="string">
            <column name="ADDRESS" not-null="true" />
        <property name="createdDate" type="timestamp">
            <column name="CREATED_DATE" length="19" not-null="true" />

hibernate.cfg.xml – Hibernate database configuration file.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">false</property>
    <mapping resource="com/mkyong/customer/hibernate/Customer.hbm.xml" />

5. Hibernate ServletContextListener

Create a ServletContextListener, and initialize the Hibernate session and store it into the servlet context.

HibernateListener .java

package com.mkyong.listener;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateListener implements ServletContextListener{
    private Configuration config;
    private SessionFactory factory;
    private String path = "/hibernate.cfg.xml";
    private static Class clazz = HibernateListener.class;
    public static final String KEY_NAME = clazz.getName();

	public void contextDestroyed(ServletContextEvent event) {
	public void contextInitialized(ServletContextEvent event) {
	 try { 
	        URL url = HibernateListener.class.getResource(path);
	        config = new Configuration().configure(url);
	        factory = config.buildSessionFactory();
	        //save the Hibernate session factory into serlvet context
	        event.getServletContext().setAttribute(KEY_NAME, factory);
	  } catch (Exception e) {

Register the listener in the web.xml file.

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >

  <display-name>Struts 2 Web Application</display-name>

6. Action

In Action class, get the Hibernate session from the servlet context and perform the Hibernate task as normal.

package com.mkyong.customer.action;

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

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.mkyong.customer.model.Customer;
import com.mkyong.listener.HibernateListener;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class CustomerAction extends ActionSupport 
	implements ModelDriven{

	Customer customer = new Customer();
	List<Customer> customerList = new ArrayList<Customer>();
	public String execute() throws Exception {
		return SUCCESS;

	public Object getModel() {
		return customer;
	public List<Customer> getCustomerList() {
		return customerList;

	public void setCustomerList(List<Customer> customerList) {
		this.customerList = customerList;

	//save customer
	public String addCustomer() throws Exception{
		//get hibernate session from the servlet context
		SessionFactory sessionFactory = 
	         (SessionFactory) ServletActionContext.getServletContext()

		Session session = sessionFactory.openSession();

		//save it
		customer.setCreatedDate(new Date());
		//reload the customer list
		customerList = null;
		customerList = session.createQuery("from Customer").list();
		return SUCCESS;
	//list all customers
	public String listCustomer() throws Exception{
		//get hibernate session from the servlet context
		SessionFactory sessionFactory = 
	         (SessionFactory) ServletActionContext.getServletContext()

		Session session = sessionFactory.openSession();

		customerList = session.createQuery("from Customer").list();
		return SUCCESS;

7. JSP page

JSP page to add and list the customer.


<%@ taglib prefix="s" uri="/struts-tags" %>
<h1>Struts 2 + Hibernate integration example</h1>

<h2>Add Customer</h2>
<s:form action="addCustomerAction" >
  <s:textfield name="name" label="Name" value="" />
  <s:textarea name="address" label="Address" value="" cols="50" rows="5" />
  <s:submit />

<h2>All Customers</h2>

<s:if test="customerList.size() > 0">
<table border="1px" cellpadding="8px">
		<th>Customer Id</th>
		<th>Created Date</th>
	<s:iterator value="customerList" status="userStatus">
			<td><s:property value="customerId" /></td>
			<td><s:property value="name" /></td>
			<td><s:property value="address" /></td>
			<td><s:date name="createdDate" format="dd/MM/yyyy" /></td>


8. struts.xml

Link it all ~

<?xml version="1.0" encoding="UTF-8" ?>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  <constant name="struts.devMode" value="true" />
  <package name="default" namespace="/" extends="struts-default">
    <action name="addCustomerAction" 
	class="com.mkyong.customer.action.CustomerAction" method="addCustomer" >
       <result name="success">pages/customer.jsp</result>
    <action name="listCustomerAction" 
	class="com.mkyong.customer.action.CustomerAction" method="listCustomer" >
        <result name="success">pages/customer.jsp</result>


9. Demo

Access the customer module : http://localhost:8080/Struts2Example/listCustomerAction.action

Struts 2 Hibernate Add Customer

Fill in the name and address fields, hits the submit button, the inserted customer details will be listed immediately.

Struts2 Hibernate List Customer


  1. Struts 2 + Hibernate integration with “Full Hibernate Plugin”
  2. ServletContextListener documentation
  3. Struts + Hibernate integration example