HIBERNATE IN CONSOLE & SERVLET

This page discusses - HIBERNATE IN CONSOLE & SERVLET

HIBERNATE IN CONSOLE & SERVLET

HIBERNATE IN CONSOLE & SERVLET
( part-3)

     

In this continuation of the earlier tutorial on Hibernate( July-2005) , the author gives a demo for using Hibernate in a console application & a servlet. 
--------
In the earlier tutorial, we had seen how we can install hibernate,& about the basic theoretical ideas of java source file of the class representing the data to be persisted, the xml mapping document for the object and the properties file for the database being used.

Hibernate can be used in stand-alone containers as well as in web-containers and ejb-containers. More often, it is used in Web-containers, through servlets. To get a clear picture of the logic, it is always advisable to test the program as a console application. Once it is found to work correctly, it is quite easy to make it a servlet program.
-------------
To begin with, we need the following files.
 
1) player.java
  2) hibernate.properties
  3) player.hbm.xml

We create all these three files as indicated below in c:\hiberdemo folder.

As in the previous example, we will consider the same player class, for continuity. The same properties file for the database ( MySql) is used. This time, we will use a slightly different mapping file (xml). We would note that there is an entry known as 'generator' in the mapping document. We had used 'hilo' generator last time. This requires that we create another table also having just one field for holding the id value. Instead of that, we will use 'increment' generator. This is straight-forward and does not require another table to be created just for holding the id.

There are different types of 'generators'.A few common types are listed below. These are used for choosing primary keys.
i) native
ii) identitty
iii) sequence
iv) increment
v) hilo
vi) uuid-hex
------ 
Hibernate supports a number of Industrial grade Databases like,
i) DB2
ii) Oracle
iii) SqlServer
iv) MySql
v) Sybase
vi) Post-greSql
vii) HyperSonic
viii) Informix
ix) Ingres
x) Interbase

----- 
The primary-key generation mechanism of each of these databases may not be uniform.
We must check up if the generator chosen by us is suitable for the database used by us. 
For our demo, we choose 'increment' generator , and it is compatible with MySql, though, it is suitable only in demo application. This generator is universally available, in all databases.
--
We begin with the player class file.
--


 //  c:\hiberdemo\player.java

public class player
{
    private  String    name;
    private  String    place;
    private  int       id;
     public player()  {     }


     public player(String a,String b)

     {
          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;    }

}
-------------------------------------------

Next, we create the properties file as before.(' hiberdemo' is the name of the MySql database created by us and the table name is 'playertable'.). Dialect is very important.and should be defined correctly.
------
c:\hiberdemo\hibernate.properties
hybernate.dialect=
net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=
com.mysql.jdbc.Driver
hybernate.connection.url=
jdbc:mysql://localhost/hiberdemo
hibernate.connection.username= 
hibernate.connection.password= 
------------------------------------------


We then create the mapping file (xml).
// c:\hiberdemo\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="player" 
table="playertable">

<id name="id" column="ID" 
unsaved-value="0">
<generator class="increment"/>
</id>

<property name="name" type="string" />
<property name="place" type="string" />
</class>

</hibernate-mapping>
=============================================


All the above files have been created in our working folder. ( c:\hiberdemo).
--
>cd c:\hiberdemo
>set path=c:\windows\command;d:\jdk1.4\bin
--------
Let us create setcpath.bat for the classpath as given below.

set classpath=
c:\hiberdemo;
c:\hibernate2\hibernate2.jar;
c:\hibernate2\lib\cglib-full-2.0.2.jar;
c:\hibernate2\lib\commons-collections-2.1.1.jar;
c:\hibernate2\lib\commons-logging-1.0.4.jar;
c:\hibernate2\lib\dom4j-1.4.jar;
c:\hibernate2\lib\ehcache-0.9.jar;
c:\hibernate2\lib\jdbc2_0-stdext.jar;
c:\hibernate2\lib\jta.jar;
c:\hibernate2\lib\log4j-1.2.8.jar;
c:\hibernate2\lib\xerces-2.4.0.jar;
c:\hibernate2\lib\xml-apis.jar;
c:\hibernate2\lib\commons-pool-1.2.jar;
c:\hibernate2\lib\commons-dpcp-1.2.1.jar;
c:\hibernate2\lib\mysqljava3.jar

( all this should be typed in a single line).
----
The last-mentioned item is the jdbcdriver for MySql.( It will not be readily available in c:\hibernate2\lib). We must download the jdbcdriver and instal this jar in hibernate2\lib folder.
( com.mysql.jdbc.Driver).
We must not forget to give the command:
>setcpath
--------------
We can check up the classpath now.
>echo %classpath%
---
We are using PHP-Triad software for MySql database. It has been given in a number of back-issues' CD's. It is very easy to instal and use. It has been installed in 
C:\ drive. From the start-menu, start mysql.
A window will appear momentarily and vanish! It shows that MySql has been started.
Now, we go to:
c:\apache\mysql\bin
--
mysql\bin>mysql

We will get the mysql prompt.
>create database hiberdemo;
>use hiberdemo;
--------------------------------------
Now, we must create a table named 
'playertable'.
--------------------------------
>create table playertable(
ID int not null primary key,
name text,
place text
);
-----------------------------
This will create the table named 
'playertable' that is being referred to in 
the mapping document.
----
Now, we are ready to create entries in 'playertable' of our database 'hiberdemo'.
--
First let us compile the player.java.
After compiling, we create the following 
console-mode program for adding, finding,
deleting, modifying and 'showall' records.
--
// c:\hiberdemo\newhiberconsole.java

import java.io.*;
import java.util.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

class newhiberconsole
{
public static void main(String args[])
{
SessionFactory factory=null;
System.out.println ("Creating factory");

try
{
Configuration cfg = 
new Configuration();
cfg.addClass(player.class);

factory = cfg.buildSessionFactory();
System.out.println("factory ready");

}
catch(Exception e1)
{ System.out.println(""+e1);}

//-----------------------------------------

try
{

DataInputStream dis =
new DataInputStream(System.in);
String s;
Transaction tx = null;
do
{
System.out.println
("add / showall/find / remove/update");

s=dis.readLine();
//---------------

if(s.equals("add"))

System.out.println("What name? ");
String a = dis.readLine(); 

System.out.println("What Place? ");
String b = dis.readLine();

try
{
Session session = factory.openSession(); 

tx = session.beginTransaction();

player player1 = new player(a,b);
session.save(player1);

tx.commit(); 
session.flush();
session.close();

System.out.println("added");
}
catch(Exception e1) 
{System.out.println(""+e1);}
}
//-------------------------------------

if(s.equals("remove"))
{
try
{
System.out.println("What key? ");
String a = dis.readLine();

Session session = factory.openSession(); 

tx = session.beginTransaction();

int i = Integer.parseInt(a); 

player player1 = (player)
session.get(player.class,new Integer(i));

session.delete(player1);
tx.commit();
session.flush();
session.close();

System.out.println("removed");
}catch(Exception e1) 
{System.out.println(""+e1);}
}
//--------------------------

if(s.equals("showall"))
{
try
{
Session session = factory.openSession();

tx = session.beginTransaction();

java.util.List list1=
session.find("from player");

Iterator i=list1.iterator();

while(i.hasNext())
{
player player1 = (player)i.next();

System.out.println(player1.getId());
System.out.println(player1.getName());
System.out.println(player1.getPlace());
System.out.println("---------------");

tx.commit();
session.flush();
session.close(); 

}catch(Exception e1) 
{System.out.println(""+e1);}
}
//-----------------------------------------

if(s.equals("find"))
{
try
{
System.out.println("What key ");
String a = dis.readLine();

Session session = factory.openSession();


tx = session.beginTransaction();


int i=Integer.parseInt(a);
player player1 = (player)
session.get(player.class,new Integer(i));


String n=player1.getName();
String m=player1.getPlace();

System.out.println(n+"\t"+m);
tx.commit();
session.flush();
session.close();


}catch(Exception e1) 
{System.out.println(""+e1);}


}
//------------------------------------------
if(s.equals("update"))
{
try
{
System.out.println("What key ");
String a = dis.readLine();
Session session = factory.openSession();


tx = session.beginTransaction();


int i=Integer.parseInt(a);
player player1 = (player)session.get(player.class,new Integer(i));
System.out.println("what name?");
String s1 = dis.readLine();

System.out.println("what place?");
String s2 = dis.readLine();

player1.setName(s1);
player1.setPlace(s2);
System.out.println("updated");
tx.commit();
session.flush();
session.close();


}catch(Exception e1)
{System.out.println(""+e1);}
}
//-----------------------------------

} while(!s.equals("over"));
}
catch(Exception e1) { System.out.println(""+e1);}
}

//============================================ 

Let us now compile the above file .
We can now add a few records and verify by giving the showall command.
We can then modify a specified record and checkup that it has indeed been modified. We can then delete.
Though the code looks so lengthy, it is actually quite simple.We first create a SessionFactory. As we have placed the player.hbm.xml file and the hibernate.properies file in the same working folder and given classpath to that folder, the program works correctly. 

MySql database , by default, does not provide transaction support, but the code will work.
We are including this pattern , just for the sake of uniformity with other databases.
=======
The actual flow is given below, from screen shot.(The first few lines about logging can be ignored. They occur because we have not set up the required logging.properties file
in our classpath.)
( user input is shown in bold)
C:\HIBERD~1>java newhiberconsole
Creating session factory
log4j:WARN No appenders could be found for
ent).
log4j:WARN Please initialize the log4j sys
sessionfactory ready
add / showall/find / remove/update
add
What name?
das
What Place?
delhi
session ready
added
add / showall/find / remove/update
add
What name?
sam
What Place?
bombay
session ready
added
add / showall/find / remove/update
showall
session ready

2
sam
bombay
---------------
1
das
delhi
---------------
Done
add / showall/find / remove/update
find
What key
2
session ready

sam bombay
Done
add / showall/find / remove/update
update
What key
2
what name?
samuel
what place?
bombay
updated
add / showall/find / remove/update
find
What key
2
session ready

samuel bombay
Done
addd / showall/find / remove/update


We are not creating any special context .
We will just use the root directory in f:\tomcat5.

We edit hiberservlet.java as given below:
=========================================
// c:\hiberdemo\hiberservlet.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class hiberservlet
extends HttpServlet
{
SessionFactory factory=null;

public void init()
{
try
{
Configuration cfg = 
new Configuration();
cfg.addClass(player.class);

factory = cfg.buildSessionFactory();
System.out.println("factory ready");

}
catch(Exception e1)
{ System.out.println(""+e1);}

}
//====================================
public void doPost
(HttpServletRequest req,
HttpServletResponse res)
throws 
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter(); 

String a = req.getParameter("text1");
String b = req.getParameter("text2");
String c = req.getParameter("text3");
String s = req.getParameter("combo1"); 

Transaction tx = null;

if(s.equals("add"))

try
{
Session session = factory.openSession();

tx = session.beginTransaction(); 
player player1 = new player(a,b);
session.save(player1);
tx.commit(); 
session.flush();
session.close();

out.println("added");
}
catch(Exception e1) 
{System.out.println(""+e1);}
}
//---------------------------------------
if(s.equals("remove"))
{
// same logic as in console app 
}
//--------------------------------------
if(s.equals("showall"))
{
// same logic as in console app


if(s.equals("find"))
{
// same logic as in console app 
}

}


===========================================
The only different thing is that we have to create sessionfactory in init() method of the servlet.
==
Let us now compile this file.

c:\hiberdemo>
>set classpath=%classpath%;
f:\tomcat5\common\lib\servlet-api.jar
-------------------
We can now compile the servlet.
After compiling, copy the following files to f:\tomcat5\webapps\root\web-inf\classes

player.class
hiberservlet.class
player.hbm.xml
hibernate.properties
-----
Whatall other jar files, we had mentioned in the classpath earlier are simply copied to :
f:\tomcat5\webapps\root\web-inf\lib

Let us remember to make the necessary entry for the servlet in web.xml file.
----------------------------

<servlet>

<servlet-name>
hiberservlet
</servlet-name>

<servlet-class>
hiberservlet
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>
hiberservlet
</servlet-name>
<url-pattern>
/servlet/hiberservlet
</url-pattern>
</servlet-mapping>

------------------------
Now create the htm file as follows:
//c:\hiberdemo\hiberservlet.htm

<html>
<body bgcolor="pink">
<form method=post
action="/servlet/hiberservlet">
Name :
<input type=text name="text1"> <br><br>
Place : 
<input type=text name="text2"> <br><br>

Key ( for remove and find) : 
<input type=text name="text3"> <br><br>

Operation :
<select name="combo1" >
<option value="add">Add
<option value="remove">Remove
<option value="find">Find
<option value="showall">Show All
</select> <br><br>
<input type=submit>
</form>
</body>
</html>

========================================
copy this htm file to:

f:\tomcat5\webapps\root
--
We go to another dos window and cd to:
f:\tomcat5\bin
>set JAVA_HOME=D:\JDK1.4
>startup
--

Start the browser and type the url as:
'http://localhost:8080/hiberservlet.htm'
--
We get the form.
Enter a name, place and select 'add' from combo and submit.
We get the message 'added'.
We can verify for other operations. 
( Verified and found to work correctly).
---
In the coming installments, we will delve into persisting Collections and the other utilities which come bundled with Hibernate , to make development very fast and easy.
--