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.

Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: water ionizer()

  • Pingback: plan()

  • Pingback: check that()

  • Pingback: certified electrician school()

  • Pingback: house blue()

  • Pingback: Google()

  • Pingback: plumbing schools in florida()

  • Pingback: k avery plumbers()

  • Pingback: locksmith i am co()

  • Pingback: electrician vs millwright 2()

  • Pingback: pay day loans()

  • Pingback: water ionizer()

  • Pingback: pay per day loans plan()

  • Pingback: water ionizer()

  • Pingback: penge laan nu()

  • Pingback: car parking()

  • Pingback: stop parking()

  • Pingback: lane penge()

  • Pingback: xnxx()

  • Pingback: Direct TV()

  • Pingback: Faux-cock and pink cigar for()

  • Pingback: Blue Coaster33()

  • prasad

    Hi sir this

  • pushpendra

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

  • asha

    hello,

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

  • 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 factory object?

    Any help is highly appreciated.
    Thank you very much…

    • http://facebook.com/wun93 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

  • ram

    nice one

  • 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

    Shut up Kumar.

  • kumar

    Good Example…

  • 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

    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

    Great article

  • Venkat

    Great article.

  • Pingback: Struts + Spring + Hibernate integration example()

  • bharat

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

  • bharat

    How to use this plugin in DAO Layer?

  • http://www.mkyong.com/struts/struts-hibernate-integration-example/ 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 validation rules file from ‘/WEB-INF/validator-rules.xml’
    May 1, 2012 1:03:30 AM org.apache.struts.validator.ValidatorPlugIn initResources
    INFO: Loading validation rules file from ‘/WEB-INF/validation.xml’
    May 1, 2012 1:03:30 AM org.apache.struts.action.ActionServlet init
    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
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.newInstance0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at org.apache.struts.util.RequestUtils.applicationInstance(RequestUtils.java:143)
    at org.apache.struts.action.ActionServlet.initModulePlugIns(ActionServlet.java:846)
    at org.apache.struts.action.ActionServlet.init(ActionServlet.java:336)
    at javax.servlet.GenericServlet.init(GenericServlet.java:211)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1044)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:876)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4017)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1083)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:789)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1083)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:478)
    at org.apache.catalina.core.StandardService.start(StandardService.java:480)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:2313)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:556)
    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:287)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:425)
    Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1340)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1189)
    … 26 more
    May 1, 2012 1:03:30 AM org.apache.catalina.core.StandardHost getDeployer
    INFO: Create Host deployer for direct deployment ( non-jmx )
    May 1, 2012 1:03:30 AM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    May 1, 2012 1:03:30 AM org.apache.jk.common.ChannelSocket init
    INFO: JK2: ajp13 listening on /0.0.0.0:8009
    May 1, 2012 1:03:30 AM org.apache.jk.server.JkMain start
    INFO: Jk running ID=0 time=0/24 config=null
    May 1, 2012 1:03:30 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 993 ms

    Please help me

  • lakshmipathy

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

  • krishna

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

  • 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 &quot;class&quot; must match &quot;(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)*)&quot;.
    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

    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

  • Prakash

    Great article

  • http://WWW.MKYONG.COM Bhargav

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

  • 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…

    • http://www.mkyong.com mkyong

      Just click on the above download link to get the full example.

      • http://www.mkyong.com/struts/struts-hibernate-integration-example/ siva

        It was nice explanation by mkyong………….thank u for ur help…..!

  • Pingback: Struts 2 + Hibernate integration example()

  • Pingback: Struts Tutorials | J2EE Web Development Tutorials()

  • Pingback: Hibernate Tutorials | Tutorials()