Newsletter |
Struts 2 Hibernate Integration Example [ Struts 2 + Hibernate Integration]
Hibernate » on May 13, 2012 { 60 Comments } By Sivateja
Let us see how to integrate struts 2 application with Hibernate, a real time application. Make sure you are well aware of the following topics before you read this article.
- Static – Core
- HQL – Hibernate
- Taking separate bean to store the values – Struts
See HibernatePlug.java, my aim is to make SessionFactory as singleton. As a programmer its our responsibulity to make SessionFactory as singleton, People used to say HibernatePlugin plugin plugin bla bla., but all it could be is to make SessionFactory as singleton, and remaining is just struts only 🙂
Directory Structure
HibernatePlug.java
package java4s; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernatePlug{ private static SessionFactory factory = getSessionFactory(); public static synchronized SessionFactory getSessionFactory() { try { Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory sessionFactory = cfg.buildSessionFactory(); System.out.println(" ---------- Factory Object Created ------------"); return sessionFactory; } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getFactory() { return factory; } }
index.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <META HTTP-EQUIV="Refresh" CONTENT="1;URL=verify.action">
retrive.jsp
<%@taglib uri="/struts-tags" prefix="s"%> <%@ page import="java.util.*,java4s.Mybean" %> <% Mybean b; %> <head> <link rel="stylesheet" type="text/css" href="css/java4s.css" /> <script type="text/javascript"> function deleteRecord() { document.fom.action="delete.action"; document.fom.submit(); } function insertRecord() { document.fom.action="insertLink.action"; document.fom.submit(); } function editr(val) { document.fom.action="update.action?fid="+val; document.fom.submit(); } </script> </head> <form method="post" name="fom"> <table> <tr><td colspan="5"> <font face="verdana" size="2"> <input type="button" value="insert" onclick="insertRecord()"> <input type="button" value="delete" onclick="deleteRecord()"> <br><br> </font> </td></tr> <tr> <td><center>+</center></td> <td><b>SNO</b></td> <td><b>SName</b></td> <td><b>Country</b></td> <td><b> Ope.</b></td> </tr> <% List l=(List)request.getAttribute("rec"); if(l!=null) { Iterator it=l.iterator(); while(it.hasNext()) { b=(java4s.Mybean)it.next(); %> <tr> <td><input type="checkbox" value="<%= b.getNo() %>" name="rdel"></td> <td><%= b.getNo() %></td> <td><%= b.getNam() %></td> <td><%= b.getCt() %></td> <td><a href="javascript:editr('<%= b.getNo() %>')">Edit</a></td> </tr> <% } } %> </table> </form>
insertScreen.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page import="java.util.*;" %> <html> <head> <link rel="stylesheet" type="text/css" href="css/java4s.css" /> <script type="text/javascript"> function display() { document.fom.action="verify.action"; document.fom.submit(); } </script> </head> <body> <s:form action="insert" name="fom"> <table> <tr> <td colspan="2"> <input type="button" value="Display Records" onclick="display()"> </td></tr> <tr><td> <s:textfield label="Number" name="b.no" cssClass="bord"/> <s:textfield label="Name" name="b.nam" cssClass="bord"/> <s:textfield label="Country" name="b.ct" cssClass="bord"/> <s:submit value="Insert" /> </td> </tr> </table> </s:form> </body> </html>
successOperation.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> Executed successfully....!!!!! <META HTTP-EQUIV="Refresh" CONTENT="1;URL=verify.action">
edit.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page import="java.util.*;" %> <html> <head> <link rel="stylesheet" type="text/css" href="css/java4s.css" /> <script type="text/javascript"> function display() { document.fom.action="verify.action"; document.fom.submit(); } </script> </head> <body> <s:form action="updateRecInDB" method="post" name="fom"> <table> <tr> <td colspan="2"> <input type="button" value="Display Records" onclick="display()"> </td></tr> <tr><td> <s:textfield label="Number" value="%{#application.x}" readonly="true" name="b.no" cssClass="bord"/> <s:textfield label="Name" value="%{#application.y}" name="b.nam" cssClass="bord"/> <s:textfield label="Country" value="%{#application.z}" name="b.ct" cssClass="bord"/> <s:submit value="Update" /> </td> </tr> </table> </s:form> </body> </html>
error.jsp
This is error page
Java4sController.java
package java4s; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ApplicationAware; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; public class Java4sController extends ActionSupport implements ServletRequestAware,ApplicationAware{ private static final long serialVersionUID = 1L; MyOperations ma = new MyOperations(); private List<Mybean> recordsFromDB; Mybean b; public Mybean getB() { return b; } public void setB(Mybean b) { this.b = b; } //For RequestAware Interface HttpServletRequest request; public void setServletRequest(HttpServletRequest request) { this.request = request; } public HttpServletRequest getServletRequest() { return request; } //For Bean, while selecting.. public List<Mybean> getRecordsFromDB() { return this.recordsFromDB; } // for ApplicationAware Interface Map m; public void setApplication(Map m) { this.m=m; } // ******* For select query ******** public String getRecords() { recordsFromDB = ma.retrieveRecords(); request.setAttribute("rec", recordsFromDB); return SUCCESS; } //********* For update query ******** public String getRecordToUpdate() { recordsFromDB = ma.retrieveRecord(request.getParameter("fid")); Iterator<Mybean> it = recordsFromDB.iterator(); while(it.hasNext()) { Object o = it.next(); b = (Mybean)o; } m.put("x",b.getNo()); m.put("y", b.getNam()); m.put("z",b.getCt()); return SUCCESS; } // ******** Insert method ********* public String insertRecord() { ma.insertRecord(b); return SUCCESS; } //********** update in database ********** public String updateRec() { ma.upRecord(b); return SUCCESS; } public String deleteRecord() { String cv[] = null; cv=request.getParameterValues("rdel"); ma.deleteRecord(cv); return SUCCESS; } }
Links.java
package java4s; public class Links{ public String insert() { return "insert"; } public String display() { return "display"; } }
Mybean.java
package java4s; public class Mybean { private int no; private String nam=""; private String ct=""; public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getNam() { return nam; } public void setNam(String nam) { this.nam = nam; } public String getCt() { return ct; } public void setCt(String ct) { this.ct = ct; } }
MyOperations.java
package java4s; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class MyOperations{ SessionFactory factory = HibernatePlug.getFactory(); Session session = factory.openSession(); Mybean p; List recList = null; public List retrieveRecords() { recList = (List<Mybean>) session.createQuery("from Mybean b").list(); System.out.println("got size"+recList.size()); return recList; } public List retrieveRecord(String val) { recList = (List<Mybean>) session.createQuery("from Mybean b where b.no="+val).list(); System.out.println("got size"+recList.size()); return recList; } public void insertRecord(Mybean p) { Transaction tx = session.beginTransaction(); session.save(p); System.out.println("Object saved successfully.....!!"); tx.commit(); } public void upRecord(Mybean p) { Transaction tx = session.beginTransaction(); Query qry = session.createQuery("update Mybean b set b.nam=?, b.ct=? where b.no="+p.getNo()); qry.setParameter(0,p.getNam()); qry.setParameter(1,p.getCt()); qry.executeUpdate(); System.out.println("Object updated successfully..."); tx.commit(); } public void deleteRecord(String cv[]) { Transaction tx = session.beginTransaction(); for(int i=0;i<cv.length;i++) { Query qry = session.createQuery("delete from Mybean b where b.no="+cv[i]); qry.executeUpdate(); } System.out.println("Object(s) deleted successfully.."); tx.commit(); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <include file="struts-default.xml"/> <package name="a" extends="struts-default"> <action name="verify" class="java4s.Java4sController" method="getRecords"> <result name="success">/retrive.jsp</result> <result name="error">/error.jsp</result> </action> <action name="update" class="java4s.Java4sController" method="getRecordToUpdate"> <result name="success">/edit.jsp</result> <result name="error">/error.jsp</result> </action> <action name="updateRecInDB" class="java4s.Java4sController" method="updateRec"> <result name="success">/successOperation.jsp</result> <result name="error">/error.jsp</result> </action> <action name="insert" class="java4s.Java4sController" method="insertRecord"> <result name="success">/successOperation.jsp</result> <result name="error">/error.jsp</result> </action> <action name="delete" class="java4s.Java4sController" method="deleteRecord"> <result name="success">/successOperation.jsp</result> <result name="error">/error.jsp</result> </action> <action name="*Link" class="java4s.Links" method="{1}"> <result name="insert">/insertScreen.jsp</result> <result name="display">/retrive.jsp</result> </action> </package> </struts>
Mybean.hbm
<?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 name="java4s.Mybean" table="details"> <id name="no" column="sno"> <generator class="assigned"/> </id> <property name="nam" column="sname" length="10"/> <property name="ct" column="scountry"/> </class> </hibernate-mapping>
hibernate.cfg.xml
<?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 name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">admin</property> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="Mybean.hbm.xml" /> </session-factory> </hibernate-configuration>
Java4s.css
.mtable { width: 300px; border: 1px solid #b0dd6f; background: #c7d8ae; border-radius: 5px 5px 0px 0px; -webkit-border-radius: 5px 5px 0px 0px; -moz-border-radius:5px 5px 0px 0px; } .mtableu { width: 300px; border: 1px solid #b0dd6f; background: #c7d8ae; border-radius: 5px 5px 0px 0px; -webkit-border-radius: 5px 5px 0px 0px; -moz-border-radius:5px 5px 0px 0px; } .th { font-family: verdana; font-size: 12px; } .td { font-family: verdana; font-size: 12px; } .bord,.label { font-family: verdana; font-size: 12px; }
Output
You Might Also Like
::. About the Author .:: | ||
Comments
60 Responses to “Struts 2 Hibernate Integration Example [ Struts 2 + Hibernate Integration]”
Thanks a lot for uploading this application Java4s. I was in very much need of this type of application…
Good application, it as useful to many programs as a base.
Thanks to java4s team
@Vaseem, @VeeraReddy
You bet 🙂
thanks much.
Great work by java4s. i just completed hibernate tutorial & done all example in netbeans ide. Just one suggestion, you should put UML diagrams of database table, so that it would easy to understand relationships by beginners. Now its time to move on spring let’s see hows it.
Thanks
@Vivek
Good to here 🙂
good program. very useful for us.. thanq for giving ..
Thanks a lot, All Example with explanation are perfect.
Easily understandable.
@Harish Chand,@KrishnaRao
You welcome friends, thanks for your feedback.
Thanks for a very nice tutorial. It would be helpful, if you can provide a zip file of the jar files to download that you used in this example. I face lot of issues in searching for the correct version of jar files that you showed in your screenshot for lib folder.
Thanks again for the wonderful tutorial.
@Greeshma
I have provided the download link, with source code including all .jar file(s). Click on ‘DOWNLOAD NOW’ button to download every thing to your local 🙂 enjoy the app.
Hi,
Where is the download link
Java4s is easy to understand ,good job
Sir Plese give the code for export pdf,excel,doc,csv & xml in struts2.
i search for this example around 50 websites but no explanation. this is only one website to understand the flow. really thanks to java4s people.
@Java4s, what is this jar “struts2-fullhibernatecore-plugin-2.2.2-GA.jar” in google code?
Great tutorials series. Good Jobs. Moving on Spring..
nice application.
thanks
nice one.!
Super app…really fantastic…..thank u very much @java4s
everything is good but, if the program had comments, then, it would have been a lot easier to newbies.
nice work,very useful
Thank You very nice example
hi shivateja plz send an application on sprins(DTO,DAO)+struts+hibernate only these things can required
Thanks a lot,good discription
Nice work ,
Very Thankful to you….
Nice work.
Hi,
Nice work…Published any books from this site?
awesome tutorials ………..
Very nice work thanks alot for helping all the learners like me…….
hi shivateja,
I worked out your program,Thanks for a very nice tutorial. if you give comments,then it will be more easier to understand the code flow.
thanks,
thank you so much..java4s…it was really helpful learning from your site…and the example were so well explained..finally I could say that now I know Struts and hibernate..and thats coz of java4s..:)
very nice tutorial for freshers and refresh basics for students
thanks to Sivateja.
The website is nice. can get to know all the hibernate concepts on the same place. Please provide an index page so that we can navigate to the pages easily. Thanks
Superb series of Struts and Hibernate…Thanks Sivateja.
Well done..
i am new to struts2 and hibernate. when i study this application i got more than i excepted nice post
ThanX a lot To TEAM.
plz, if possible give an example of hibernate and struts2 integration with the help of annotations. thanks
The above example is working fine…thanks for you great work..
also please provide a simple example with spring + struts2 + hibernate
Thank god somehow i found this site otherwise i would have struggled a lot to understand this concept,very useful, you made me learn on my own thanks a lot..
The main plus point in your website is easy to understand by any one,rich look and with the good stuff so what is the need to go for the other websites,I did not see any website like this.Really Great.We will thank full to you Sivateja.
Hello Java4s,
I was the person who first commented this article.
You are doing a great job by making us learn java in an easy manner.
I just wanted to know that the coding methods/standards presented in this article is depicting to what coding standards industry follows.
I know that for a beginner this is the recommended site to have
Thanks for looking my post.
Cheers,
Mohammed Vaseem.
Hello ,
It is really nice website that any one can learn and explore very easily.
It helped me a lot..
Thanks a lot .. 🙂
Hi Shiva ,
i have some problem for understood your please clear my confusion .
you have used in your edit jsp {value=”%{#application.x}”} like that in there what represent application keyword . Please give me reply as soon possible as.
Great Work I Just Love To Visit Java4s Everytime..Good Explanation and I succesfully completed my struts classes now time to move Spring..java4s is nothing but enjoy the programming Good Luck 🙂
Really nice…………it will be very much helpful to continue…
Thanks a lot Bro !!
Besides the navigation everything is good. Please introduce index in the left for simple navigation
Thank you… It’s worth to read you’re document.
If the purporce of HibernatePlug is singleton then why did you make getSessionFactory()as public?
Nice work Bro!!
I am fully clear on concepts of hibernate
Hi sir this program is not executing properly it shows errors while insert the data like
”
javax.servlet.ServletException: org.hibernate.exception.DataException: Could not execute JDBC batch update
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)” can you please rectify this problem.
Sir this program is not updating the database.please suggest me.
Hi Sir
plz added more Interview Questions With answer..
hai sir ,
i have one problem with the program,cna we write a statement like this in the programe
private static SessionFactory factory = getSessionFactory();
hi shivateja,
I worked out your program,Thanks for a very nice tutorial.if you possible just provide one example on Connection Pooling in hibernate.
Thanks Sir,
your tutorial is very good and easy to understand.
Great example. Helped me a lot 🙂
Respected Author!
Your examples are extra-ordinary!
only one point i would like to specify is please give comments in the code. you have implemented the code with Oracle as database. when we try with other database we feel difficult to follow! Please specify what software you have used for front end also. since we are using Netbeans I am unable to get .settings folder as you specified in your directory structure
Please do provide database name, table name and the fields to be created.
Very nice tutorial… it's easy to understand for beginners.. Thanks
Nice article on Struts. Keep it up dude.
Greeting ,
can you please make one flow diagram on this.