Saturday, April 29, 2017

How to integrate Struts and Hibernate

Hi everybody,



  Today's article, I would like to explain how to integrate Struts and Hibernate framework. First of all, I would like to explain that I am using the MVC pattern to configure it. Struts is my VIEW and CONTROLLER and Hibernate will be the MODEL.

 

Steps of the integration :

  • Configure the plug-in property on struts-config or in another class to setup the configuration of the file .cfg.xml.
  • Create a Hibernate - Struts plugin to set the Hibernate session factory in the servlet context based on the previous setup.
  • Then get the Hibernate  session factory from the servlet context and call/execute whatever Hibernate task needed.

Step-by-step:

   1.0- In my case, I've created a util class called HibernateUtil.java where I am setting up the CreateSessionFactory as below.


   1.1 - You can also do the same dynamic step above manually inserting the Hibernate config XML plugin in struts-config.xml as below:<struts-config>
  1.     ...
        <plug-in className="com.mkyong.common.plugin.HibernatePluginThiago">
           <set-property property="path" value="/hibernate.cfg.xml"/>
        </plug-in>
     ...
    <struts-config
I prefer the first option as you keep your code reusing as much as possible code.


2.0 - On the same scenario, HibernateUtil is where you reference the struts-config.xml parameters and add the datasource session picking up the methods as below:




As you can see the datasouirce is called THIAGO-DB, and this is configured thru all methods that belongs to HibernateUtil.java.

3.0 - Next and final step now is get the Hibernate session factory thru the DAO object that you need to configure. The suggestion that I have is keep as much dynamic as possible in order to make it very easy to change later, as needed.

Here it's the piece of code that I've created to call the session factory from my Hibernate configuration in Struts.

You can see in my try-catch block above that I am calling the current session of HibernateUtil instance that has the THIAGO_DB configuration. So, you are now getting the session factory configured to Hibernate in Struts framework.


I hope this helps, happy coding.
Thiago Leoncio.



No comments:

Post a Comment