Struts + Hibernate integration example
A tutorial to show how to integrate Hibernate with in a web application developed with Apache Struts 1.x.
Download It – Struts-Hibernate-Example.zip
Steps of the integration :
- 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.
- 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.
can you please explain this statement (private static Class clazz = HibernatePlugin.class;) thank you
Hello,
If im using convention over configuration for struts2 then how can i include the hibernate config file ?
what is the mysql 5.1.10 compatible Hibernate latest version?
you are a genius!!!!!!
Hi sir this
I am following your blog long ago now still. i find it difficult to understand this concept
hello,
I am getting following error.
HTTP Status 404 – There is no Action mapped for namespace / and action name register.
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 »
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
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…
Shut up Kumar.
Good Example…
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
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
Great article
Great article.
[…] Struts + Hibernate example […]
How do we use Hibernate Integration in DAO Layer by using the above example
How to use this plugin in DAO Layer?
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 »
i tried to get the connection in a jsp but am not getting action servlet in jsp
getting null for this statement clazz.getResource(path);
please help me.This is an urgent
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
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)
Great article
I have Learned from this site Programs & Please Provide Descriptive Also For the Particular Program
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…
Just click on the above download link to get the full example.
It was nice explanation by mkyong………….thank u for ur help…..!
[…] 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 […]
[…] Struts + Hibernate integration Example to integrate the Struts with Hibernate framework. […]
[…] Struts + Hibernate Integration Example to integrate Hibernate with Struts framework. […]
nice one