Struts 2-Hibernate 3 integration(complete) using eclipse

2 Sep

hi

i am going to give you complete example of struts 2.0.11 and hibernate 3 integration

well let me start from eclipse configuration,i am using eclipse 3.3 for development,it is nice and stable

step1- create Dynamic web project in eclipse .

step2- now i am going to give configuration of struts 2.0.11 in project open web.xml

and add struts filter for applying struts 2 ,write this in web.xml in

<filter>
    <filter-name>struts-cleanup</filter>
    <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter>
</filter>
<filter>
    <filter-name>struts2</filter>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter>
</filter>
<filter-mapping>
    <filter-name>struts-cleanup</filter>
    <url-pattern>/*</url>
</filter>
<filter-mapping>
    <filter-name>struts2</filter>
    <url-pattern>/*</url>
</filter>

Another thing you have to do is to put (create) struts.xml file in src folder of eclipse

and put required library for struts (common-logging.jar,freemarker.jar,ognl.jar,struts2-

core.jar, xwork.jar)

This is basic configuration for struts 2

Step-3 now it is time to configure hibernate with struts for that we required hibernate and its required

Libraries in web-Inf/lib folder, complete list:

antlr.jar, asm.jar, cglib.jar, commons-beanutils.jar, common-logging.jar, dom4j.jar

freemarker.jar, hibernate.jar, jta.jar, <jdbc drivers libs>, ognl.jar, struts2.jar, xwork.jar

Step4-we have to create session factory of hibernate in struts 2 filter, so we will extend struts 2 filter,

Create class in src folder for create plugin of hibernate

In your own package structure, I have create HibernateUtil.java in org.hns.plugin

HibernateUtil.java

package org.hns.plugin;

    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.Session;

    public class HibernateUtil {
    private static SessionFactory sessionFactory;
    public static void createSessionFactory() {
    sessionFactory = new Configuration().configure().buildSessionFactory();
    }
    public static Session getSession() {
    return sessionFactory.openSession();
    }
}

Struts2dispatcher.java

package org.hns.plugin;

import javax.servlet.*;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.hibernate.HibernateException;
    
 public class Struts2Dispatcher extends FilterDispatcher {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    super.init(filterConfig);
    try {
    HibernateUtil.createSessionFactory();
    System.out.print("application initializing successfully");
    } catch (HibernateException e) {
    throw new ServletException(e);
    }
  }

}

Step-5

package org.hns.plugin;

import javax.servlet.*;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.hibernate.HibernateException;

public class Struts2Dispatcher extends FilterDispatcher {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    super.init(filterConfig);
    try {
    HibernateUtil.createSessionFactory();
    System.out.print("application initializing successfully");
    } catch (HibernateException e) {
    throw new ServletException(e);
    }
  }
}

Step-6 - apply this filter in web.xml like

<!--<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> -->

    <filter-class>org.hns.plugin.Struts2Dispatcher</filter-class>

Step-7 we have to put hibernate configuration file in src folder with the name hibernate.cfg.xml
Give your connection url, username, password, jdbc driver class name, for this example I have used mysql database

I have used user schema with usr  username and password, in user schema there is usermast table with the field usercode(int),uname(varchar),pwd(varchar),type(varchar), you can create table and put 2-3 dummy entry in your wishing database.

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">   
 
<hibernate-configuration>
<session-factory>
<property>true</property>
<property name="connection.characterEncoding">UTF-8</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/user</property>
<property>usr</property>
<property>usr</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property>org.hibernate.transaction.JDBCTransactionFactory</property>


 
</session-factory>
</hibernate-configuration>

Step-8

It is time to create hibernate mapping with table and mapping class

I have created User.java in org.hns.user package

package org.hns.user.;
public class User
{
  private int id;
  private String username;
  private String password;
  private String usertype;
    // add fields setter and getter here (required)
}

Create User.hbm.xml in org.hns.user (org/hns/user/ OR where User.java created) like

    <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class table="usermast">
   <id column="usercode">
    <generator></generator>
   </id>
   <property column="uname" name="username">
   <property column="pwd">
   <property column="type">
  </class>
</hibernate-mapping>

You can get more idea about any another advance mapping stuff from any hibernate tutorial.

Here property is java class variable name and column is table column name.

Step-9 add user hbm mapping to hibernate.cfg.xml using below code between sessionfactory tag

 
<mapping resource="org/hns/user/User.hbm.xml">

 the basic settings for using hibernate for usermast table has been completed here.
Step-10

now I am create another java file UserHibDao.java in  org.hns.user.dao  for create and access user dao

package org.hns.user.dao;
   import java.util.List;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    import org.hns.user.User;
    import org.sm.plugin.HibernateUtil;
    public class UserHibDao {
    private List<user> userlist;
    private User user;
    public void delete(Integer id) {
    Session session = HibernateUtil.getSession();
    Transaction tx = null;
    try
   {
   tx = session.beginTransaction();
    user=(User)session.get(User.class,id);
    session.delete(user);
    tx.commit();
    }catch (RuntimeException e) {
    if(tx != null) tx.rollback();
    throw e;
    } finally {
    session.close();
    }
    }
    public List getAllUser() {
    Session session = HibernateUtil.getSession();
    try
    {
    session.beginTransaction();
    userlist=session.createQuery("from User").list();
    return userlist;
    }
    catch(Exception e)
    {
    System.out.print("Error while fetching "+e);
    return null;
    }
    finally
    {
    session.close();
    }
    }
    public User getuser(Integer id) {
   Session session = HibernateUtil.getSession();
    try {
    session.beginTransaction();
    //change query for get proper data
    Query q = session.createQuery("from User u where u.uid=:id");
    q.setInteger("userid",id);
    return (User) q.uniqueResult();
    }finally {
    session.close();
    }
    }
    public void insert(User usr) {
    Session session = HibernateUtil.getSession();
    Transaction tx=null;
    try {
    tx = session.beginTransaction();
    session.save(usr);
    tx.commit();
    } catch (RuntimeException e) {
    if(tx != null) tx.rollback();
    throw e;
    } finally {
    session.close();
    }
    }
    public void update(User usr) {
    Session session = HibernateUtil.getSession();
    Transaction tx = null;
    try {
    tx=session.beginTransaction();
    session.update(usr);
    tx.commit();
    }catch (RuntimeException e) {
    if(tx != null) tx.rollback();
    throw e;
    } finally {
    session.close();
    }
    }
  }
 

So after this stuff you can either use this class for creating service layer of dao or you can use this class functions directly for set business logic.
here one thing should be noted that hibernate query fire on its class object not directly on table so i have used

somthing like this session.createQuery(“from User u where u.uid=:id”); instead of using session.createQuery(“from usermast u where u.uid=:id”);[tablename query]

hope this is enough to start with struts 2 and hibernate 3 ,if you feel still there is some stuff missing in this blog ,let me know from comment

Thanks :-)))

About these ads

43 Responses to “Struts 2-Hibernate 3 integration(complete) using eclipse”

  1. Mohnish September 3, 2008 at 10:41 am #

    Thnx :)

  2. Satyendra September 8, 2008 at 5:37 am #

    May i get bloggin example using struts and hibernate.

  3. Satyendra September 8, 2008 at 5:39 am #

    May i get bloggin example using struts and hibernate

  4. Majid October 9, 2008 at 11:54 am #

    Thank you very much, I would like to have the complete struts-hibernate example, please your help is appreciated.

    Thanks again

  5. swara October 29, 2008 at 3:33 pm #

    Please post the full struts2 hibernate example….waiting for ur reply

  6. saivenkat October 31, 2008 at 2:33 pm #

    I Appreciate this Example Strus 2 with Hibernate3

  7. saivenkat October 31, 2008 at 2:35 pm #

    it would be good if it takes the values from jsp page and insert it into database using hibernate

  8. viralpatel.net January 8, 2009 at 1:28 am #

    Hi Hardik,
    Nice tutorial.
    Similar tutorial is Struts Application using Eclipse.
    Do post tutorials frequently.. Waiting to see more..

  9. Sunil Vashisth January 15, 2009 at 4:52 am #

    Thanks for the effort you have put in writing this article. But it ends with an abruptly.
    I've created a DAO now what?
    Some screenshots would have been helpful.

  10. Nath March 21, 2009 at 12:25 am #

    It would have been still good if you had included a sessionBean to call those methods

    and also UI tags of struts2.

  11. Indrajeet kumar April 1, 2009 at 10:13 am #

    Great Work!

    Indrajeet
    indrajeetkr2002@yahoo.co.in

  12. Jigar Naik April 6, 2009 at 4:31 am #

    Great !

  13. murugan April 20, 2009 at 6:36 am #

    how to call main function in this example?

  14. Unileally May 18, 2009 at 8:31 pm #

    well.. it's like I said!

  15. Abdullah June 4, 2009 at 6:28 am #

    I am trying to make a login page using Hibernate 3 and struts 2 .. after
    I deploy using Myeclipse , I get problem of this sort cited below… Please help me I am stuck badly and no one is there to help me..

    Caused by: java.lang.InstantiationException: com.opensymphony.xwork2.interceptor.Interceptor
    at java.lang.Class.newInstance0(Class.java:335)
    at java.lang.Class.newInstance(Class.java:303)
    at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:123)
    at org.apache.struts2.plexus.PlexusObjectFactory.lookup(PlexusObjectFactory.java:298)
    at org.apache.struts2.plexus.PlexusObjectFactory.buildBean(PlexusObjectFactory.java:216)
    at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:154)
    at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:143)
    at org.apache.struts2.plexus.PlexusObjectFactory.buildInterceptor(PlexusObjectFactory.java:146)
    … 153 more
    11:35:52,003 INFO [STDOUT] 11:35:52,003 WARN [InterceptorBuilder] Unable to load config class com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor at Class: java.lang.Class
    File: Class.java
    Method: newInstance0
    Line: 335 – java/lang/Class.java:335:-1 probably due to a missing jar, which might be fine if you never plan to use the scoped-model-driven interceptor
    11:35:52,007 INFO [STDOUT] 11:35:52,003 ERROR [InterceptorBuilder] Actual exception
    Unable to instantiate an instance of Interceptor class [com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor]. – Class: java.lang.Class
    File: Class.java
    Method: newInstance0

  16. Rajesh June 17, 2009 at 11:56 pm #

    Superb work, Easy to understand

  17. Card Tricks July 28, 2009 at 5:01 am #

    Thank you!!
    I was googling for days to find good tutorials, but all of them made me loose my patience since little things were not working from the beginning.
    Your tutorial was straight forward, and most importantly: WORKING!
    thanks!

    Card tricks

  18. Keith August 4, 2009 at 11:10 am #

    Thanks for this sample, I have tried to use this for my app. I have a couple of minor changes as I am trying to use Annotaitions over XML, but I am getting an error:
    HTTP Status 500 -
    type Exception report
    message
    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
    exception
    java.lang.reflect.InvocationTargetException
    note The full stack traces of the exception and its root causes are available in the GlassFish/v3 logs.

    appear in the browser window, debugging shows this occurs at the point of

    HibernateUtil
    [sessionFactory = (new AnnotationConfiguration()).configure().buildSessionFactory();]

  19. kislay August 7, 2009 at 2:23 pm #

    Nice tutorial, but please try to explain from JSP till DB connection pooling.

    Thanks

  20. José Yoshiriro September 1, 2009 at 11:21 am #

    The most of the job could be evicted using the Full Hibernate Plugin for Struts2.

  21. José Yoshiriro October 14, 2009 at 4:34 pm #

    There is a plugin the “Full Hibernate Plugin” that provites quick integration between Struts2 and Hibernate.

    http://cwiki.apache.org/S2PLUGINS/full-hibernate-plugin.html

    A very good tutorial:
    http://www.vaannila.com/struts-2/struts-2-example/struts-2-hibernate-integration-1.html

  22. Raj December 24, 2009 at 5:59 am #

    Thanks for this sample, But u didn't give the code how to communicate the jsp form data with ->struts2 ->hibernate file ……..

  23. Andrew A. Sailer January 15, 2010 at 10:08 pm #

    I found your post on my (almost) daily obsession with blog searching. Thanks for the informative blog post as I can certainly appreciate all of the hard work that goes into maintaining a site like this! Thanks again.

  24. shweta March 10, 2010 at 1:41 pm #

    Thanks. very informative

  25. nadh April 8, 2010 at 1:27 am #

    this is nice tutorial and easy to understand but where exactly struts frame works takes help to access dao layer?

  26. Eduardolutt June 21, 2010 at 8:21 am #

    This is the best tutorial i seen .. thanks

  27. Harish Thakkar September 10, 2010 at 1:11 am #

    Compilation is going on.
    Will share the result once it gets competed.

  28. ester September 10, 2010 at 10:22 am #

    Great tutorial.
    Can i Have an example of Struts2, HIbernate3 Mysql Login application please?
    Thanks

  29. prakash November 12, 2010 at 2:23 am #

    hi
    Thanks, good information is there.
    I need good url links to understand struts,spring,hibernate frame works, if any member know plse send the mail to:na_prakash_19@yahoo.co.in

  30. [...] on these 2 tecnologies?   Bruno Bossola, Co-founder of GitEnterprise.com – Ent… http://hardik4u.wordpress.com/20http://www.vaannila.com/struts-2…8:21amView All 0 CommentsCannot add comment at this [...]

  31. samba March 8, 2011 at 3:37 am #

    hi write saple example.

    and u write create session factory.
    private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new AnnotationConfiguration().configure() .buildSessionFactory(); } catch (Throwable ex) { System.err.println(“Initial SessionFactory creation failed.” + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
    and u write dao class.
    and u write dto class
    and u write struts execite method(—-);
    and u write hbmapping file.
    and u write table

  32. Sreedhar rao September 20, 2011 at 8:08 am #

    good.

  33. Bhaskar January 28, 2012 at 5:49 am #

    Hi whenever i try to change my web.xml file with the modified Struts2Dispatcher file i get an error message. Can you please help?

  34. Zanboneyguyxz June 19, 2012 at 12:45 am #

    Thanks! I like this site. The content kepted me reading for a while. This is interesting stuff. I will be checking for new posts daily.
    ______________________________
    Virginia Beach Roofing Company

  35. Donte Delpaggio June 19, 2012 at 10:41 pm #

    I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!…

  36. Jann Wuitschick June 20, 2012 at 1:16 am #

    I adore your blog post.. Comfortable colours & motif. Does a person design and style this amazing site on your own or maybe do anyone bring in help to make it work in your case? Plz react seeing that I!|m aiming to style my personal website and would want to learn exactly where ough obtained this kind of out of. Thank you

  37. sports bh June 20, 2012 at 11:53 am #

    I have adopted your blog for quite a while and must say that this time an individual hit the particular nail along with precision since never, I have almost exactly the same thought and ideals as you've, keep coming with gold articles like this and you will have a follower for a lifetime!

  38. Michel Zakar June 20, 2012 at 4:41 pm #

    Oh my goodness! an amazing article dude. Thank you However I am experiencing issue with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting identical rss problem? Anyone who knows kindly respond. Thnkx

  39. Madelyn Loreto June 20, 2012 at 5:20 pm #

    You should take part in a contest for one of the best blogs on the web. I will recommend this site!

  40. pinky July 4, 2012 at 11:24 pm #

    PLZ give me a login and registration form example

  41. prashansa July 13, 2012 at 3:06 am #

    sir it is an amazing article
    Can i Have an example of Struts2, HIbernate3 Mysql Login application please?

  42. Gaurav February 11, 2013 at 2:24 am #

    can you please upload the struts.xml file because i am not able to execute my program because of lack of knowledge of struts

  43. http://blogg.gausen.net/ May 10, 2013 at 7:03 am #

    Asking questions are actually nice thing if you are not
    understanding something entirely, however this piece of writing gives nice understanding
    yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: