|
Advertisement |
USING HIBERNATE WITH STRUTS - 2
Posted On June 20, 2010 by Shruthi S filed under Open Source
Struts is the most popular MVC framework for the web today. Similarly, Hibernate is the most popular ORM tool( Object-Relational- Mapping) tool in j2ee world. My tutorial is about integrating Hibernate and Struts, in a simple example.
There is no more change in struts-config.xml file. We enter the details as such as a normal struts application has.
In the struts-config.xml file, we make two entries. One entry is for the instance of hiberForm and the other entry is for the instance of hiberAction class.
Go to a new window.
cd to g:\tomcat5\webapps\hiberapp\web-inf >
edit struts-config.xml
Make the following changes.
------------------------------------------
<form-bean name="hiberForm" type="hiberpack.hiberForm" />
The next segment of mapping in
struts-config.xml deals with the action mapping for hiberAction.
<action path="/hiber" type="hiberpack.hiberAction" name="hiberForm" input="/hiberSubmit.jsp" scope="session" validate="true">
<forward name="success" path="/hiberSubmit.jsp"/>
</action>
------------------------------------------
Actually Struts does not deal with business logic atall. We can use any data-access technology of our choice for performing business logic.
There are various options like JDBC,JDO, Hibernate and even CMP/BMP which can be used along with Struts.
However, CMP seems to have gone out of favour and nowadays, Hibernate has become the defacto standard.
I will begin with the required files for Struts.
1) hiberSubmit.jsp
2) hiberForm.java
3) hiberAction.java
4) besthiberbean.java [helper class]
I am using hiberSubit.jsp itself to display the result itself! It will appear as if the GUI retained , as in a desktop application.
In our example, we will perform the standard CRUD operations using Hibernate in a helper class.I have named this helper class as
'besthiberbean'.
Apart from this, there is no difference in the concept of other jsp and java files used in Struts. They follow the standard pattern.
There have been a few tutoriuals on Hibernate in earlier issues. I will use MySql database just as done in those articles.
I here use the table 'playertable' of database'hiberdemo'.Table1 has three columns namely id,name,place.
Procedure:
g:\>md hiberapp
g:\>cd hiberapp
g:\hiberapp>md hiberpack
g:\hiberapp>cd hiberpack
set path as :
d:\windows\system32;
c:\jdk1.5\bin
...........>set classpath=
g:\hiberapp;
cglib-full-2.0.2.jar;
commons-collections-2.1.1.jar;
commons-logging-1.0.4.jar;
dom4j-1.4.jar;ehcache-0.9.jar;
jdbc2_0-stdext.jar;
jta.jar;
log4j-1.2.8.jar;
xerces-2.4.0.jar;
xml-apis.jar;
hibernate2.jar;
commons-pool-1.2.jar;
commons-dpcp-1.2.1.jar;
mysqldriver.jar;
f:\jars\struts.jar;
g:\tomcat5\common\lib\servlet-api.jar
copy needed jar files for compiling hibernate file to parent folder and mention them in class path also. ( when dealing with
jar files for classpath, it is not enough to simply mention the folder where they are present. Each jar should be specifically mentioned).
hiberSubmit.jsp has three textfields[key, name,place], a combo box [ has CRUD operations like showall,find,add,delete,modify] textarea
[for showing the result]and submit button.
hiberSubmit.jsp
==============
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<body bgcolor=aqua text=blue>
<html:errors />
This is query page <br>
<html:form action="hiber" name="hiberForm" type="hiberpack.hiberForm" >
<%
String r= (String)session.getAttribute("result");
%>
<br>
NAME<html:text property="name" /> <br>
PLACE <html:text property="place" /> <br>
KEY<html:text property="id" /> <br>
OPERATION<html:select property="op">
<option value="add">add</option>
<option value="update">update</option>
<option value="find">find</option>
<option value="showall">showall</option>
<option value="remove">remove</option>
</html:select>
<html:submit /> <br>
RESULT <br>
<html:textarea property="result" rows="15" cols="30" value="<%= r %>" />
</html:form>
</body>
</html>
*****************************************************
hiberForm.java
==============
package hiberpack;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class hiberForm extends
ActionForm
{
String name=null;
String place=null;
String id=null;
String op=null;
String result=null;
//-----------------------------------
public String getName()
{ return name; }
public String getPlace()
{ return place; }
public String getId()
{ return id; }
public String getOp()
{ return op; }
public String getResult()
{ return result; }
//--------------------------------------
public void setName(String a)
{
name=a;
}
public void setPlace(String b)
{ place=b; }
public void setId(String c)
{ id=c; }
public void setOp(String d)
{ op=d; }
public void setResult(String e)
{ result=e; }
//-----------------------------------
public void reset(ActionMapping mapping,
HttpServletRequest request)
{
name=null;
place=null;
id=null;
op=null;
result=null;
}
}
**************************************************
hiberAction.java
=================
package hiberpack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class besthiberAction extends Action
{
public ActionForward execute
(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
hiberForm hiberform =(hiberForm) form;
String a = hiberform.getName();
String b = hiberform.getPlace();
String c = hiberform.getId();
String d = hiberform.getOp();
String e = hiberform.getResult();
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
//---------------------------------------
besthiberbean bean = new besthiberbean();
System.out.println("bean ready");
String r = bean.edit(a,b,c,d);
HttpSession session = request.getSession();
session.setAttribute("result",r);
return (mapping.findForward("success"));
}
}
Before compiling these struts files we have to compile besthiberbean file.[helper file]
we require
besthiberbean.java
player.java
player.hbm.xml
hibernate.properties
We have to place hiberbean,player and mapping xml file in the same place where we have our struts files.So, these three files should be at hiberpack. But properties file should be out from package.So, we have to place it under the parent folder[hiberapp].
This is very important point.
besthiberbean.java
(in hiberapp\hiberpack folder)
===================
package hiberpack;
import java.io.*;
import java.util.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
public class besthiberbean
{
public String edit
(String a, String b, String c, String d)
{
SessionFactory factory=null;
System.out.println("Creating session factory");
String r="";
try
{
Configuration cfg =
new Configuration();
cfg.addClass(player.class);
factory = cfg.buildSessionFactory();
System.out.println("sessionfactory ready");
Transaction tx = null;
Session session = factory.openSession();
tx = session.beginTransaction();
//------------------------------------
if(d.equals("add"))
{
int i=Integer.parseInt(c);
player player1 = new player(i,a,b);
session.save(player1);
r="added";
}
//---------------------------------
if(d.equals("remove"))
{
int i = Integer.parseInt(c);
player player1 =(player)session.get
(player.class,new Integer(i));
session.delete(player1);
r=" record removed";
}
//-----------------------------------
if(d.equals("showall"))
{
java.util.List list1=session.find
("from player");
Iterator i=list1.iterator();
while(i.hasNext())
{
r=r+"\n";
player player1 = (player)i.next();
System.out.println(player1.getId());
r=r+player1.getId()+"\t";
System.out.println(player1.getName());
r=r+player1.getName()+"\t";
System.out.println(player1.getPlace());
r=r+player1.getPlace();
System.out.println("---------------");
}
}
//-----------------------------------------
if(d.equals("find"))
{
int i=Integer.parseInt(c);
player player1 = (player)session.get
(player.class,new Integer(i));
String n=player1.getName();
String m=player1.getPlace();
System.out.println(n+"\t"+m);
r=c+"....."+n+"....."+m;
}
//-------------------------------------
if(d.equals("update"))
{
int i=Integer.parseInt(c);
player player1 =(player)session.get
(player.class,new Integer(i));
player1.setName(a);
player1.setPlace(b);
r="updated";
}
//--------------------------------------
tx.commit();
session.flush();
session.close();
System.out.println("done.....");
}catch(Exception e1) {r=""+e1;}
return r;
}
}
*******************************************************
player.java
============
package hiberpack;
public class player
{
String name;
String place;
int id;
public player()
{
}
public player(String a,String b)
{
name=a;
place=b;
}
public player(int i,String a,String b)
{
id=i;
name=a;
place=b;
}
public String getName()
{
return name;
}
public void setName(String a)
{
name = a;
}
public String getPlace()
{
return place;
}
public void setPlace(String b)
{
place = b;
}
public int getId()
{
return id;
}
public void setId(int s)
{
id = s;
}
}
**********************************************************
player.hbm.xml
==============
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="hiberpack.player"
table="playertable">
<id name="id" column="ID" unsaved-value="0">
<generator class="assigned"/>
</id>
<property name="name" type="string" />
<property name="place" type="string" />
</class>
</hibernate-mapping>
********************************************************
hibernate.properties
====================
hibernate.dialect=
net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=
com.mysql.jdbc.Driver
hibernate.connection.url=
jdbc:mysql://localhost/keynameplace
hibernate.connection.username
hibernate.connection.password
***********************************************
I will now give the procedure.
compile the java files.
g:\hiberapp\hiberpack>javac player.java
....>javac besthiberbean.java
....>javac hiberForm.java
....>javac hiberAction.java
Rename the struts-blank folder as hiberapp and create hiberpack under classes folder.Then,
copy
1)hiberForm.class
2)hiberAction.class
3)besthiberbean.class
4)player.class
5)player.hbm.xml to
g:\tomcat5\webapps\hiberapp\web-inf\
classes\hiberpack folder.
copy hibernate.properties to
g:\tomcat5\webapps\hiberapp\web-inf\classes
folder.
copy all the jar files in parent folder to
g:\tomcat5\webapps\hiberapp\web-inf\lib folder.
copy hiberSubmit.jsp file to
g:\tomcat5\webapps\hiberapp folder.
hiberSubmit itself acts as input and output file.
Start the tomcat server.Type the url in browser
as
http://localhost:8080/hiberapp/hiberSubmit.jsp
We will be able to carry out all the five operations.
( add, edit, remove, find and showall).
We successfully integrated struts and hibernate.
======================================================





