Struts + Hibernate integration example

A tutorial to show how to integrate Hibernate with in a web application developed with Apache Struts 1.x.

Steps of the integration :

  1. Create a new Hibernate Struts plug-in file to set the Hibernate session factory in servlet context, and include this file in struts-config.xml file.
  2. In Struts, get the Hibernate session factory from servlet context, and do whatever Hibernate task you want.

1. Hibernate Struts Plug-in

Create a Hibernate Struts Plug-in, get the Hibernate session factory, store it into the servlet context for later user – servlet.getServletContext().setAttribute(KEY_NAME, factory);.


package com.mkyong.common.plugin;

import java.net.URL;
import javax.servlet.ServletException;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernatePlugin implements PlugIn {
   private Configuration config;
   private SessionFactory factory;
   private String path = "/hibernate.cfg.xml";
   private static Class clazz = HibernatePlugin.class;

   public static final String KEY_NAME = clazz.getName();

   public void setPath(String path) {
      this.path = path;
   }

   public void init(ActionServlet servlet, ModuleConfig modConfig)
      throws ServletException {

      try {
    	  
    	 //save the Hibernate session factory into serlvet context
         URL url = HibernatePlugin.class.getResource(path);
         config = new Configuration().configure(url);
         factory = config.buildSessionFactory();
         servlet.getServletContext().setAttribute(KEY_NAME, factory);

      } catch (MappingException e) {
         throw new ServletException();
      } catch (HibernateException e) {
         throw new ServletException();
      }

   }

   public void destroy() {
      try {
         factory.close();
      } catch (HibernateException e) {
         e.printStackTrace();
      }
   }
}

2. struts-config.xml

Include the Hibernate Struts plug-in into the Struts configuration file (struts-config.xml).


<struts-config>
    ...
    <plug-in className="com.mkyong.common.plugin.HibernatePlugin">
      	<set-property property="path" value="/hibernate.cfg.xml"/>
    </plug-in>
	...
<struts-config>

3. Get the Hibernate session factory

In Struts action class, you can get the Hibernate session factory from servlet context.


servlet.getServletContext().getAttribute(HibernatePlugin.KEY_NAME);

and do whatever Hibernate task as normal.


package com.mkyong.customer.action;
 
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.mkyong.common.plugin.HibernatePlugin;
import com.mkyong.customer.form.CustomerForm;
import com.mkyong.customer.model.Customer;
 
public class AddCustomerAction extends Action{
 
  public ActionForward execute(ActionMapping mapping,ActionForm form,
	HttpServletRequest request,HttpServletResponse response) 
  throws Exception {
 
        SessionFactory sessionFactory = 
	         (SessionFactory) servlet.getServletContext()
                            .getAttribute(HibernatePlugin.KEY_NAME);

	Session session = sessionFactory.openSession();
		
	CustomerForm customerForm = (CustomerForm)form;
	Customer customer = new Customer();
		
	//copy customerform to model
	BeanUtils.copyProperties(customer, customerForm);
		
	//save it
	customer.setCreatedDate(new Date());
		
	session.beginTransaction();
	session.save(customer);
	session.getTransaction().commit();
		
	return mapping.findForward("success");
	  
  }
}

Done.

About the Author

author image
mkyong
Founder of Mkyong.com, 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.

Comments

Leave a Reply

avatar
newest oldest most voted
Genaro Gx
Guest
Genaro Gx

can you please explain this statement (private static Class clazz = HibernatePlugin.class;) thank you

Hish
Guest
Hish

Hello,

If im using convention over configuration for struts2 then how can i include the hibernate config file ?

ssb
Guest
ssb

what is the mysql 5.1.10 compatible Hibernate latest version?

Aamir Khan
Guest
Aamir Khan

you are a genius!!!!!!

prasad
Guest
prasad

Hi sir this

pushpendra
Guest
pushpendra

I am following your blog long ago now still. i find it difficult to understand this concept

asha
Guest
asha

hello,

I am getting following error.
HTTP Status 404 – There is no Action mapped for namespace / and action name register.

ravikumar
Guest
ravikumar
Hello All, It is a very great website for the java developers. Thank you so much for your assistance. I could manage to run the above application successfully without any errors.But i have some doubts in the application. Could anybody please help me in this regard? The doubt is as follows,In the given application the business logic and Data access logic are mixed at one place. I think it is better to split the business logic code and dao code in to two different places. How to develop the DAO pattern with above Hibernate plugin? How to get the session… Read more »
quân chùa
Guest
quân chùa

It’s just a tutorial to show how to integrate both frameworks into one web application.
In a real web project must be more rules and of course .
let me say it again . THIS TURORIAL IS NOT ABOUT STRUCTURAL WEB APPLICATION

santosh nayak
Guest
santosh nayak

I am getting following error.
SEVERE: Unable to initialize Struts ActionServlet due to an unexpected exception or error thrown, so marking the servlet as unavailable. Most likely, this is due to an incorrect or missing library dependency.
java.lang.NoClassDefFoundError: org/hibernate/HibernateException
more…

Can anybody plz help me…

Harold
Guest
Harold

Shut up Kumar.

kumar
Guest
kumar

Good Example…

Aman
Guest
Aman

Sorry but you didn’t write code of retrieve values from database using WHERE condition in query in struts+hibernate
please send me code for above on my email-id
Thanks

Pratap
Guest
Pratap

Hi Mykong I deploy ur application i am getting the following error.

31/01/2013 6:56:32 PM org.apache.catalina.core.ApplicationContext log
SEVERE: action: null
java.lang.ClassCastException: com.org.vo.HibernatePlugin cannot be cast to org.apache.struts.action.PlugIn
at org.apache.struts.action.ActionServlet.initModulePlugIns(ActionServlet.java:842)
at org.apache.struts.action.ActionServlet.init(ActionServlet.java:359)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1206)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
31/01/2013 6:56:32 PM org.apache.catalina.core.ApplicationContext log

Venkat
Guest
Venkat

Great article

Venkat
Guest
Venkat

Great article.

trackback
Struts + Spring + Hibernate integration example

[…] Struts + Hibernate example […]

bharat
Guest
bharat

How do we use Hibernate Integration in DAO Layer by using the above example

bharat
Guest
bharat

How to use this plugin in DAO Layer?

Srinivas
Guest
Srinivas
Hi Sir, I am trying to integrate sturts and hibernate, iam getting the below error May 1, 2012 1:03:29 AM org.apache.coyote.http11.Http11Protocol init INFO: Initializing Coyote HTTP/1.1 on http-8080 May 1, 2012 1:03:29 AM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 604 ms May 1, 2012 1:03:29 AM org.apache.catalina.core.StandardService start INFO: Starting service Catalina May 1, 2012 1:03:29 AM org.apache.catalina.core.StandardEngine start INFO: Starting Servlet Engine: Apache Tomcat/5.0.30 May 1, 2012 1:03:29 AM org.apache.catalina.core.StandardHost start INFO: XML validation disabled May 1, 2012 1:03:30 AM org.apache.struts.tiles.TilesPlugin initDefinitionsFactory INFO: Tiles definition factory loaded for module ”. May 1, 2012 1:03:30 AM org.apache.struts.validator.ValidatorPlugIn initResources INFO: Loading… Read more »
lakshmipathy
Guest
lakshmipathy

i tried to get the connection in a jsp but am not getting action servlet in jsp

krishna
Guest
krishna

getting null for this statement clazz.getResource(path);
please help me.This is an urgent

Upendra
Guest
Upendra
Dear mkyoung

Thanks for a very nice tutorial. I m trying to test it integrating with my sample struts application. But i stuck somewhere and problems seems related to the version of hibernate library.
I am using  hibernate 4.0.1.
Error messages are like
2012/02/28 16:32:02 org.hibernate.internal.util.xml.ErrorLogger error
ERROR: HHH000196: Error parsing XML (13) : The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,fetch-profile*,resultset*,(query|sql-query)*)".
Above exception is being thrown from following code of HibernatePlugin.java.
config = new Configuration().configure(url);
Can the cause of the problem be guessed with the info provided above??

Thanks in advance.
-Upendra
Joseph
Guest
Joseph

Hello,

when launching the server tomcat 6
I get the following error:

Unable to initialize Struts ActionServlet due to an unexpected exception or error thrown, so marking the servlet as unavailable. Most likely, this is due to an incorrect or missing library dependency

dpr
Guest
dpr

Getting Servlet unavailable exception

12:36:17,234 ERROR [[/]] StrutsController: null

java.lang.NullPointerException

at org.hibernate.cfg.Configuration.configure(Configuration.java:1441)

at com.aims.hibernate.common.util.HibernatePlugin.init(HibernatePlugin.java:32)

Prakash
Guest
Prakash

Great article

Bhargav
Guest
Bhargav

I have Learned from this site Programs & Please Provide Descriptive Also For the Particular Program

Herat
Guest
Herat

please send me the demo application of struts hibernate integration application.as i dont know this framework.
I want to work in this framework..but i am bit confused in folder structure and mapping file placed in netbeans and eclipse id..
Please help me out of this…

trackback
Struts 2 + Hibernate integration example

[…] 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 […]

trackback
Struts Tutorials | J2EE Web Development Tutorials

[…] Struts + Hibernate integration Example to integrate the Struts with Hibernate framework. […]

trackback
Hibernate Tutorials | Tutorials

[…] Struts + Hibernate Integration Example to integrate Hibernate with Struts framework. […]

ram
Guest
ram

nice one