Sie sind auf Seite 1von 24

HIBERNATE- BASICS

(R.S.Ramaswamy)- ( in 3 parts)
(part-1)
( CMP-EJB vs. HIBERNATE)
(published in DeveloperIQ-July-2005)

The J2EE field is agog with excitement about a very popular open-source technology ,
Hibernate , being elevated to the status of JCP standard. Feedback from J2EE programmers in
industry says that knowledge of Hibernate is mandatory for all J2EE aspirants.In this short
tutorial , the author attempts to trace the reasons for this new trend & to alert us , to the
imminent and dramatic changes in the J2EE landscape.

HIBERNATE is an ORM ( Object-Relational-Mapping) technology. It is an Open-Source


and free technology , developed in SourceForge.net. There have been a number of such
ORM technologies, in recent past.. TopLink is one such tool , subsequently adopted by
Oracle and so proprietary. Hibernate from SourceForge and OJB(Object-Relational-Bridge)
from Apache are two well known ORM tools, open-source and free. JDO, also falls within
the same category.

Gavin King is the lead for Hibernate and Craig Russell & David Jordan, the lead authors
for SUN-sponsored JDO effort. Due to some technical problems, it appears that the majority
in JCP favours Hibernate today instead of JDO. At first reading though, the difference is not,
all that apparent. The syntax and the approach appear to be almost same, but Hibernate
syntax is easier to learn.

It is interesting to note that Craig Russell works for SUN and Gavin King is now with JBoss.
It shows that JCP is a democratic community and SUN is not dictating terms except to protect
the language and its enterprise-level users.

EJB-3, is the latest version and it is heavily influenced by Hibernate. Some readers equate
EJB-3 with Hibernate. Some even equate EJB-3 with JBOSS! Oracle supports EJB-3
proposals and as it is the main Database company in j2ee world, EJB-3 has bright future.
J2EE( Java Enterprise Edition) by its very name is an Enterprise level technology, and as EJB
is the essence of such Enterprise applications, because of the built-in container services
offered, the significance of the surging interest in Hibernate can be really appreciated only in
association with EJB and hence a detour into EJB is inevitable.

EJB has three types. One type is the SESSION BEAN,residing in ENTERPRISE container,
which can be thought of as a function-bean, invoked in RMI-IIOP style.(this is a rough
definition). Such session-bean , may be either stateless or stateful. This type of EJB has stood
the test of time during the last six years and has even gained wide approval,even for data-
access, especially since it fits very well with the emerging XML WebService technology, and
is very easy to learn and implement.( The earlier tutorial on EJB as webservice in Feb-2005,
in DeveloperIQ illustrates this feature). The stateless bean working in Enterprise container
has an exact counter-part in Microsoft COM+(MTS). but the other types are said to be
available in MS platform only through third-party extensions.
ORM tools have been sometimes used along with Session beans. The only problem till
recently was that they were proprietory and rather costly. But nowadays, very reliable open-
source ORM tools are available, and even Richard Monson Haefel ( an acknowledged
authority and author on EJB)approves this method as a safe and productive alternative to
Entity beans.( page-467..EJB by Haefel-OReilly).

The other branch, the ENTITY BEAN has been less lucky. EJB-1.1,EJB-2.0 and then EJB-
2.1 , have meant a number of changes in the specification relating to Entity Beans.
We can say that an Entity bean is an 'Attribute bean' or 'property-bean', with setter and getter
methods, invoked in RMI-IIOP style and persisted in Enterprise container. The pattern of
defining a typical Javabean is a recurring theme in Java. The same style occurs in BDK,EJB-
Entity beans, Struts,JSF and now in Hibernate too. So, it is very important and elegant.

The third branch is Messaging paradigm and MDB. A recent article in the web dubbed the
'RPC' style, on which the previous two types of EJB are based, as stone-age technologies! An
Enterprise by its very name implies huge number of customers and concurrent transactions,
RPC style being like telephone call, could result in 'line-engaged!' problem.If the call
involves the called person referring to some records before replying, it leads to line-
blocking.But, messaging style, as in email, atleast ensures that the message has been sent.It
is evident that dubbing RPC( read 'telephone') as unsuitable , is over-statement.Sometimes,
we desire immediate response,too. By the same token, even XML webservice , if it is really
serious, should adopt messaging style and it does.MDB (Message-Driven bean) has
weathered the storm and is in fact gaining more and more acceptance.

So, why is it that Entity beans alone were found wanting and the specification keeps on
changing?
Entity beans are of two types. CMP & BMP.
CMP stands for Container-Managed Persistence and BMP stands for Bean-managed
persistence. Theoretically, the EJB specification does not say anything about the method to
be adopted in persisting objects for permanent storage and retrieval. It could be simple object
serialization. The database may be object-database or Object-relational database or XML.In
practice , however, a database has always meant a Relational Database and its SQL.

In a very complex Enterprise application, we begin with Modelling. Instead of dealing with
tables and their complex inter-relations, it is more intuitive to deal with classes and objects.
Thus we design our system , 'thinking in objects' and not in tables. So long, as we are
dealing with objects in memory or with objects persisted in hard-disk simply as objects, there
is no problem, except that object-serialization , especially of complex objects is a slow
process. On the other-hand, Relational Database technology is fast, time-tested, well-known
and famous. So, the problem is to work with objects in memory but persist the objects in hard
disk as relational database.
This is what is known as ORM ( Object-Relational Mapping).If we opt to deal directly with
tables only and either read data or manipulate data by session beans, we skip the entire ORM
problem.But how practical is it for really complex projects?That is the rationale for the
development of Entity Beans in EJB.

In CMP, the coder deals with objects, only in memory. He creates new objects, modifies
them, deletes them and views them , all in memory. The task of saving these objects in
memory ,to the relational database table is done by the container, automatically. The coder
does not write any sql-related code for this.
In BMP, the coder has to write the sql to persist the object in memory to the relational
database.

CMP in EJB1.1 was suitable for simple tables, without complex relationships to other
tables.CMP avoids all references to the underlying database. So, it is more portable. There is
no vendor-lock-in.CMP can persist data to Object- databases also, besides Relational
databases.

But, CMP is not always suitable. If the database is some legacy type, which cannot be used
with SQL, the database company gives a proprietory code for persistence and such code has
to be used in our program to persist data. The facilities given in CMP originally were found
to be too elementary and there were complaints.

But, what matters is that CMP makes use of ORM concepts, though the implementation left
much to be desired. It did not expose how the EJB vendor implements
it.Weblogic,Oracle,IBM WebSphere, SUN ,JBoss , each may implement CMP in any way
that they deem fit.Except in special circumstances, it will be better to use CMP, not merely
because, it makes the code more portable & is easy to write. Much more important reason is
that the EJB container can optimize the performace dramatically, if we adopt CMP.So the
developer community wanted to adopt CMP but found it unsuitable for really complex jobs.

And a sizable section of developers found the XML Deployment Descriptors for CMP ,
especially for complex jobs, a bit troublesome and tedious.It can be said that any design
which makes us dependent on wizards, is a bad design. Unlike the Deployment
Descriptors for Session beans, which can be hand-coded in a jiffy, by just find/replace
method in a text editor, the DD for CMP required three XML files, two of them very special
to the container used.

In order to improve things, EJB 2.0 proposed a few changes, mainly in the matter of writing
CMP. It provided for Relationships. It proposed a simple query language known as 'EJB-QL'.
Since, calling an Entity bean through a session bean (Facade pattern) is more efficient , from
the viewpoint of minimizing network traffic, the very concept of remote interface for entity
beans was questioned and so local interface also was provided for Entity beans.( In a total
reversal, there is no local interface in EJB-3! and instead of EJB-QL , Hybernate Query
Langauge is taking over in EJB-3).

Even with all these improvements, CMP was found to be less than the ultimate solution.
There was no possibility for Inheritance.

Though the container services provided by the EJB container are indispensable in a truly
large enterprise application, the J2EE camp is almost vertically split into WebTier & EJB-
Tier votaries. The WebTier supporters claim that EJB with its steep learning curve and error
prone development environment for developers is not really necessary for most applications.
And they would like to have an ORM tool , built into the J2EE specification. For afterall,
ORM task is not specific to EJB alone. Even Servlets and JSP could use them. In fact , they
have been using them, though the J2EE specification was silent about it. ORM tools like
OJB, JDO and Hibernate can be used not only in EJB containers but in webcontainer and
even in standalone containers. Gavin King makes it a special point in favour of
Hibernate.Making such a tool , a J2EE standard, would make development tasks far easier ,to
develop either web-tier application or ejb-tier application. saving us from the medley of
classpath to required jars.
In a scathing attack on the complexity and questionable performance of EJB Entity beans
(though, unjustifiably on EJB itself), Rod Johnson, prophesies , that in a few years' time,
J2EE will cease to include EJB.Whether , we agree or not, it is worth looking into the
criticisms against EJB Entity beans ,raised by him.( 'J2EE Development without EJB'-
Wrox/Wiley/DreamTech-2004).For, he is proposing the Spring Framework as an alternative
to EJB container and the idea is gaining ground.J2EE developers and students may have to
re-orient themselves rather abruptly, to remain relevant to industry.

HIBERNATE-BASICS
Hibernate Performing the usual DB operations

(part-2)

In this second part of the tutorial, the author outlines the basic features of the Hibernate
environment and the code for performing the usual DB operations.

Hybernate2 can be downloaded from http://www.hibernate.org. We can unzip and install it


in any directory of our choice. In our case, it is c:\hibernate2. If we look in c:\hibernate2
folder, we find hibernate2.jar. Besides this, we find a number of jar files in the
c:\hibernate2\lib folder.

The following important jar files are available in c:\hibernate2\lib .


-----------------------------------------
cglib2.jar,
commons-collections.jar
commons-Logging.jar
dom4j.jar
ehcache.jar
jdbc2.0-stdext.jar
log4j.jar
xerces.jar
xml-apis.jar
----------------------------------------
The hibernate2.jar & all the above jar files have to be placed in our classpath. As mentioned
already, hibernate can be used in standalone application, web-application or in EJB. This
facilitates easy testing without having to deploy either in web-container or in EJB-container.

So, we can create our working folder as:


c:\hiberdemo.

In the next step , we can create a setpath.bat file in c:\hiberdemo


as:
set path=c:\windows\command;d:\jdk1.4\bin

Next, we can create a setcpath.bat to include c:\hibernate2\hibernate2.jar and similarly all


the abovementioned jar files. This must be carefully typed and checked thoroughly for
correctness. (This will be pretty lengthy.)

We CD to c:\hiberdemo and give two commands to set the path & classpath.
---
We have to create four files
in c:\hiberdemo.
---------------------------------------
1) hibernate.properties
( this is known as hibernate configuration file). This file is used to give details of the
Database used by us for hibernate.

2) We want to create a java class, which will be automatically persisted to Relational


Database, by hibernate.
This class follows the standard Javabeans convention. In our example ,it is player.java.

3) We must create a mapping document. This is an XML document. , typically,


player.hbm.xml

4) The fourth file is our stand-alone application to test and use hibernate.We can have a
simple frame program with 4 buttons for add, modify, delete and find operations. We can call
it hiberframe.

5) We should have installed the relevant Database software , referred to in the


hibernate.properties file.

-----------------------------------------
We can use a number of databases with Hibernate. We have chosen MySql for our example.

A typical properties file is given below.


( this is for MySql database).
---------------------------------------
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=
----------------------------------------
This can also be written as an XML file hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>


<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration
DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver">
com.mysql.jdbc.Driver
</property>
<property name="connection">
jdbc:mysql://localhost/players
</property>
<property name="dialect">
net.sf.hibernate.dialect.MySQLDialect
</property>
</session-factory>
</hibernate-configuration>

This file speaks of MySql jdbc driver. We must obtain the software and place it in
c:\hibernate2\lib and then include it in our classpath.
****************************************
Next, we create the player.class file as shown below.
---
// 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;
}
}
*****************************************

This is just the usual JavaBean file. We must strictly follow the JavaBean convention. It must
have a public no-args constructor.
It has another constructor, too.

We can easily compile this file to get player.class. This class will be referred to in the
mapping document, known by the name
player.hbm.xml, given below.

-----------------------------------------
// 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="player">
<id name="id" type="int" unsaved-value="null">
<column name="ID" sql-type="int" not-null="true" />
<generator class="hilo"/>
</id>
<property name="name" type="string"/>
<property name="place" type="string"/>
</class>
</hibernate-mapping>

==========================================
Having created all these files, we can now write the code for a simple framedemo. (The gui
code is not given here. We need not use Swing. All that we require is a set of four buttons
and a text area for display of result.

The gui code fragment will be as follows:


As our player class has name & place values, we provide two textboxes for adding new
values. The text3 is for criteria for finding.
We provide 5 buttons (add, modify, remove, find, showall).
In a textarea, we display the message.

In the constructor

hiberdemo()

...

....

panel1.add(text1);
panel1.add(text2);
panel1.add(text3);
panel2.add(TextArea);
panel3.add(button1);
..
panel3.add(button5);
//-------------------------

That takes care of the gui.


We must have the following imports.

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

In the constructor itself, we have to initialize the SessionFactory, using try-catch block.

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

factory = cfg.buildSessionFactory();
area1.setText("factory ready");
} catch(Exception e1){
area1.setText(""+e1);
}
-------------------------------------
The code creates a new configuration object and tries to load the mapping document for the
class specified in the addClass() method.

To build a Session object a session factory object needs to be instantiated from the
Configuration object. The constructor assumes there is a class attribute defined as follows:
factory =null;
The buildSessionFactory() method builds a factory based on the specifics of mapping
document processed by Configuration object.

After thus initialising, we can write code smippets for add, modify, delete & find.
**************************************

The code for adding is

String a = text1.getText();// name


String b = text2.getText();// place
try
{
Session session = factory.openSession();
Transaction tx = null;
tx = session.beginTransaction();
player player1 = new player(a,b);
session.save(player1);
tx.commit();
session.flush();
session.close();
area1.setText("added");
}catch(Exception e1) {
area1.setText(""+e1);
}
----------------------

The above steps are very easy to comprehend. A new object is created in memory with the
given name and place and is persisted in the player table. The required SQL is automatically
generated by Hibernate and carried out.
-----
The Session object handles all the work involved in saving, updating and loading objects
from permanent storage. A Session should be invoked for a short time, to save or to load an
object. One of the most important actions performed by the Session object is creating a
connection to the database. The session object includes methods save(), update() and
saveOrUpdate()
==========================================

Thus, for creating eeither add or update or delete or find operation, we first create the session
object:

Session session=factory.openSession();
Then we begin the transaction.
After either creating a new object or getting a reefereence to the required object, we perform
the operation.
For adding,
session.save(palyer1);
For updating,
player1.setName(
player1.setPlace(
as required and then,
session.update();
--
Finally,
for deleting, get a reference to the object to be deleted and give the command;
session.delete(player1);
===
If we want to find an object by its id, we can use ,
session.find(player.class, id);
--
It is always better to carry out all these operations within a transaction. James Eliot in
'Hibernate -A developer's notebook'(OReilly) reports that he found that persistence was not
done well without transaction.( page-46).

The following code section also will occur for each operation.
tx.commit();

session.flush();
session.close();

*******************************************

Hibernate can persist objects with complex attributes like collections and other objects. It
supports very involved relationships. It also provides its own
simple query language known as HQL. We have Query objects also. There are what are
known as Criteria queries. Advanced features like Hibernate Annotations have been
developed. Thus, we have barely touched the surface of a deep subject. We will see these
topics in some detail in future issues.

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.

Das könnte Ihnen auch gefallen