Struts 2 + Spring + Hibernate integration example

In this tutorial, it shows the integration between “Struts2 + Spring + Hibernate“. Make sure you check the following tutorials before continue.

  1. Struts 2 + Hibernate integration example
  2. Struts 2 + Spring integration example
  3. Struts 1.x + Spring + Hibernate integration example

See the summary of integration steps :

  1. Get all the dependency libraries (a lot).
  2. Register Spring’s ContextLoaderListener to integrate Struts 2 and Spring.
  3. Use Spring’s LocalSessionFactoryBean to integrate Spring and Hibernate.
  4. Done, all connected.

See the relationship :

Struts 2 <-- (ContextLoaderListener) --> Spring <-- (LocalSessionFactoryBean) --> Hibernate
This will be a very long tutorial with little explanation, make sure you check the above 3 articles for details explanation.

Tutorials Start…

It will going to create a customer page, with add customer and list customer function. Front end is using Struts 2 to display, Spring as the dependency injection engine, and Hibernate to doing the database operation. Let start…

1. Project structure

Project folder structure.

Struts2 Spring Hibernate Project Structure
Struts2 Spring Hibernate Project Structure

2. MySQL table script

Customer’s table script.

DROP TABLE IF EXISTS `mkyong`.`customer`;
CREATE TABLE  `mkyong`.`customer` (

3.Dependency libraries

This tutorials request many dependency libraries.

Struts 2…

        <!-- Struts 2 -->
	<!-- Struts 2 + Spring plugins -->


        <!-- MySQL database driver -->


    <!-- Spring framework --> 


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

4. Hibernate…

Only the model and mapping files are required, because Spring will handle the Hibernate configuration. – 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"
<!-- Generated 20 Julai 2010 11:40:18 AM by Hibernate Tools 3.2.5.Beta -->
    <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" />

5. Struts 2…

Implements the Bo and DAO design pattern. All the Bo and DAO will be DI by Spring in the Spring bean configuration file. In the DAO, make it extends Spring’s HibernateDaoSupport to integrate Spring and Hibernate integration.

import java.util.List;
import com.mkyong.customer.model.Customer;
public interface CustomerBo{
	void addCustomer(Customer customer);
	List<Customer> listCustomer();

import java.util.List;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;
public class CustomerBoImpl implements CustomerBo{
	CustomerDAO customerDAO;
	//DI via Spring
	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	//call DAO to save customer
	public void addCustomer(Customer customer){
	//call DAO to return customers
	public List<Customer> listCustomer(){
		return customerDAO.listCustomer();

package com.mkyong.customer.dao;
import java.util.List;
import com.mkyong.customer.model.Customer;
public interface CustomerDAO{
	void addCustomer(Customer customer);
	List<Customer> listCustomer();	

package com.mkyong.customer.dao.impl;
import java.util.List;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;
public class CustomerDAOImpl extends HibernateDaoSupport 
    implements CustomerDAO{
	//add the customer
	public void addCustomer(Customer customer){
	//return all the customers in list
	public List<Customer> listCustomer(){
		return getHibernateTemplate().find("from Customer");		
} – The Struts2 action is no longer need to extends the ActionSupport, Spring will handle it.

package com.mkyong.customer.action;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.mkyong.customer.model.Customer;
import com.opensymphony.xwork2.ModelDriven;
public class CustomerAction implements ModelDriven{
	Customer customer = new Customer();
	List<Customer> customerList = new ArrayList<Customer>();
	CustomerBo customerBo;
	//DI via Spring
	public void setCustomerBo(CustomerBo customerBo) {
		this.customerBo = customerBo;
	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{
		//save it
		customer.setCreatedDate(new Date());
		//reload the customer list
		customerList = null;
		customerList = customerBo.listCustomer();
		return "success";
	//list all customers
	public String listCustomer() throws Exception{
		customerList = customerBo.listCustomer();
		return "success";

6. Spring…

Almost all the configuration is done here, at all, Spring is specialized in integration work :).

CustomerBean.xml – Declare the Spring’s beans : Action, BO and DAO.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 	<bean id="customerAction" class="com.mkyong.customer.action.CustomerAction">
		<property name="customerBo" ref="customerBo" />	
	<bean id="customerBo" class="" >
		<property name="customerDAO" ref="customerDAO" />
   	<bean id="customerDAO" class="com.mkyong.customer.dao.impl.CustomerDAOImpl" >
		<property name="sessionFactory" ref="sessionFactory" />
</beans> – Declare the database details.


DataSource.xml – Create a datasource bean.

<beans xmlns=""
   <property name="location">
  <bean id="dataSource" 
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />

HibernateSessionFactory.xml – Create a sessionFactory bean to integrate Spring and Hibernate.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
<!-- Hibernate session factory -->
<bean id="sessionFactory" 
    <property name="dataSource">
      <ref bean="dataSource"/>
    <property name="hibernateProperties">
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
    <property name="mappingResources">

SpringBeans.xml – Create a core Spring’s bean configuration file, act as the central bean management.

<beans xmlns=""
	<!-- Database Configuration -->
	<import resource="config/spring/DataSource.xml"/>
	<import resource="config/spring/HibernateSessionFactory.xml"/>
	<!-- Beans Declaration -->
	<import resource="com/mkyong/customer/spring/CustomerBean.xml"/>

7. JSP page

JSP page to display the element with Struts 2 tags.


<%@ taglib prefix="s" uri="/struts-tags" %>
<h1>Struts 2 + Spring + 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="customerAction" method="addCustomer" >
		    <result name="success">pages/customer.jsp</result>
		<action name="listCustomerAction"
			class="customerAction" method="listCustomer" >
		    <result name="success">pages/customer.jsp</result>

9. Struts 2 + Spring

To integrate Struts 2 and Spring, just register the ContextLoaderListener listener class, define a “contextConfigLocation” parameter to ask Spring container to parse the “SpringBeans.xml” instead of the default “applicationContext.xml“.


 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >
  <display-name>Struts 2 Web Application</display-name>

10. Demo

Test it : http://localhost:8080/Struts2Example/listCustomerAction.action

Struts2 Spring Hibernate Example
Struts2 Spring Hibernate Example


  1. Struts 2 + Hibernate integration example
  2. Struts 2 + Spring integration example
  3. Struts 2 + Hibernate example with Full Hibernate Plugin
  4. Struts 1.x + Spring + Hibernate integration example
Tags :

About the Author

Founder of and, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.


  • Pingback: read more()

  • Pingback: cheap car insurance()

  • Pingback: water ionizer loans()

  • Pingback: pay per day loans plan()

  • Pingback: pay per day loan plans()

  • Pingback: Google()

  • Pingback: water ionizer()

  • Pingback: electrician salary range()

  • Pingback: electrical licensing requirements()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrk√≥w trybunalski()

  • Pingback: alkaline water brands()

  • Pingback: a locksmith naples florida()

  • Pingback: journeyman electrical jobs()

  • Pingback: water ionizer()

  • Pingback: car parking()

  • Pingback: water ionizer()

  • Pingback: alkaline water machine()

  • Pingback: sms laan nu()

  • Pingback: parking()

  • Pingback: youporn()

  • Pingback: lan penge nu 18 ar()

  • Pingback: lan penge nu uden sikkerhed()

  • Pingback: DIRECTV channels()

  • Pingback: get satellite tv()

  • Pingback: watch movies online()

  • Pingback: weight loss()

  • Pingback: Blue Coaster33()

  • vicky

    Can you provide me the working code sample with latest version of struts ,spring and hibernate combination?

    appreciate your quick response.

    Thanks in advance.

  • tareq

    Dear mkyong,

    It’s a good work, but I am facing a issue when I am starting Apache Tomcat from Netbeans, please see below error message from Apache Tomcat Log:

    Oct 9, 2013 5:14:57 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    Oct 9, 2013 5:14:59 PM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/classes/config/spring/HibernateSessionFactory.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
    at Method)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(
    at org.apache.catalina.core.StandardContext.listenerStart(
    at org.apache.catalina.core.StandardContext$
    at org.apache.catalina.core.StandardContext$
    at java.util.concurrent.FutureTask$Sync.innerRun(
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(
    at java.util.concurrent.ThreadPoolExecutor$
    Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(
    at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.(
    at org.hibernate.tuple.entity.EntityMetamodel.(
    at org.hibernate.persister.entity.AbstractEntityPersister.(
    at org.hibernate.persister.entity.SingleTableEntityPersister.(
    at org.hibernate.persister.PersisterFactory.createClassPersister(
    at org.hibernate.impl.SessionFactoryImpl.(
    at org.hibernate.cfg.Configuration.buildSessionFactory(
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(
    … 23 more
    Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
    at java.lang.reflect.Constructor.newInstance(
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(
    … 36 more
    Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.(I)V
    at net.sf.cglib.core.DebuggingClassWriter.(
    at net.sf.cglib.core.DefaultGeneratorStrategy.getClassWriter(
    at net.sf.cglib.core.DefaultGeneratorStrategy.generate(
    at net.sf.cglib.core.AbstractClassGenerator.create(
    at net.sf.cglib.core.KeyFactory$Generator.create(
    at net.sf.cglib.core.KeyFactory.create(
    at net.sf.cglib.core.KeyFactory.create(
    at net.sf.cglib.core.KeyFactory.create(
    at net.sf.cglib.proxy.Enhancer.(
    at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(
    at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(
    at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.(
    at org.hibernate.tuple.entity.PojoEntityTuplizer.(
    … 41 more
    Oct 9, 2013 5:14:59 PM org.apache.catalina.core.ApplicationContext log
    INFO: Closing Spring root WebApplicationContext

    Can you please let me know the fix of this issue.

    Info: I have already resolved following issue “Missing artifact javax.transaction:jta:jar:1.0.1B” which I was getting at the time of building maven project.

    Thank you.


  • Patty

    I am getting an error : Missing artifact javax.transaction:jta:jar:1.0.1B – do you know how can I resolve this. I just changed the versions to include latest libraries and made a progress only upto creating the pom.xml

  • Pingback: Missing artifact javax.transaction:jta:jar:1.0.1B | BlogoSfera()

  • Puneet Pant

    Some Jars can not be distributed even by:
    So download it from Oracle/sun and install with options
    -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar

  • Bob

    Could you provide the list of jar files please?

    I did download your source code but can not run correctly because of build path:(
    Thanks very much !

  • Thanh

    If I use sql instead of mysql, how can i change the


  • Albano

    As usual a good example but, there is a behaviour that scares me: if you refresh the page, the last submitted values are inserted again.

  • Huynh Thanh Toan

    Although I follow your step but I can not run it
    Please help me !!!
    Thankss !!!

  • xl twin mattress topper

    Attractive section of content. I just stumbled upon your site
    and in accession capital to assert that I acquire actually enjoyed account your blog posts.
    Anyway I will be subscribing to your feeds and even I achievement you
    access consistently quickly.

  • Sadye

    I was suggested this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my problem.
    You are incredible! Thanks!

  • marius

    Can this project be used with annotations in spring and hibernate or do I have to change dependencies ?

  • Tran Van Dung


    I’m integrated tiles 2 into Struts2 + Spring + Hibernate project. However it doesn’t work.

    Please help me.


  • http://none El Houcine


    It’s a good work, but I want to create the project structure by myself on eclipse, so I want to know all steps that you are followed to create the project structure.


  • y

    [ERROR] Failed to execute goal on project Struts2Example: Could not resolve dependencies for project
    com.mkyong.common:Struts2Example:war:com.mkyong.common: Failure to find javax.transaction:jta:jar:1
    .0.1B in was cached in the local repository, resolution will not
    be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]

    [ERROR] No goals have been specified for this build. You must specify a valid lifecycle phase or a g
    oal in the format : or :[:
    ]:. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, g
    enerate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-
    sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test,
    prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, ins
    tall, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
    org.apache.maven.lifecycle.NoGoalSpecifiedException: No goals have been specified for this build. Yo
    u must specify a valid lifecycle phase or a goal in the format : or :[:]:. Available lifecycle phases are: validate, ini
    tialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-
    classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resource
    s, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integra
    tion-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, s
    ite, post-site, site-deploy.
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(
    at org.apache.maven.DefaultMaven.doExecute(
    at org.apache.maven.DefaultMaven.execute(
    at org.apache.maven.cli.MavenCli.execute(
    at org.apache.maven.cli.MavenCli.doMain(
    at org.apache.maven.cli.MavenCli.main(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(

    If you are literate in Chinese, please reply to Chinese, thank you.

  • Hamza


    if you want to use both files. hbm and annotated classes, how to make when creating “session factory” to use the “AnnotationSessionFactoryBean” and “LocalSessionFactoryBean”.