Open Source Java Tools - Hibernate and Eclipse

P.Madhanasekaran

Hibernate is the most popular Object Relational Mapping tool. As we program in java, for that matter in any object oriented programming language, the business logic is represented in terms of objects and their interactions.  But only relational databases rule the roost in the databases sphere. If we want to persist or, store the objects-in-memory in such a database we have to think in terms of tables and columns. Thus there is an inherent mismatch between the objects-in-memory and the means to persist them. The tools that help the programmer in handling this “mismatch paradigm” are called Object Relational Mapping tools(ORMs). Hibernate from Sourceforge.net is one such tool. The entity beans of EJB also serve the same purpose. Then Why ORMs have popular, while entity beans have almost fallen into disuse? To know the reasons thereof and it for a sound understanding of the concepts and the code used here, readers are advised to refer to the comprehensive and comprehensible introduction to Hibernate by Shri. R.S.Ramasamy  available in “in.geocities.com”  and  in August and September 2005 issues of DeveloperIq. The purpose of present article is more to show how to use the tool with Eclipse. Eclipse needs no introduction. There are a few eclipse plugins like Synchronizer, or Hibernator from SourceForge.net that ease the use of hibernate in Eclipse IDE. To use it in a servlet, a Tomcat project has to be created and this requires “Sysdeo Tomcat plugin” and for the steps involved, my earlier article “Struts in Eclipse IDE with Sysdeo Tomcat plugin” can be referred to. But to write a stand alone hibernate program, default Eclipse installation is enough and no plugin is needed.  Hibernate makes use of only Plain Old Java Objects and java classes implementing “special” interfaces or “specific” environments are not required. Hibernate can be used in different environments- managed environment in an application server like JBoss or in non-managed environment of a stand-alone application It enables the programmer to provide the mapping information in  xml files(Declarative management) and avoid spraying them all over the code . We will look into how to use hibernate in a stand-alone java program created in Eclipse3.1 IDE

 Let us begin with creating a database by name hiberdemo in another open source tool  Mysql  and create a table “playertable” with three columns 1)”ID” type integer Auto increment ,2) “name” type varchar ,3)”place”  type varchar   and insert some data into the table .We will use  Hibernate to persists objects into this table. We need a java class to instantiate objects to be persisted and we will create a class “player.java” with  attributes i) id int, 2)name String, 3)place String with getter and setter methods. Hibernate provides persistence service and it is highly configurable. The Configuration information given enable hibernate to obtain database connections.  This information is given in a properties file called “hibernate properties” or an XML file “hibernate-cfg.xml”. These files contain the database connection parameters like 1)the jdbc driver to use 2)database to connect to 3) the username and 4) password 5)database dialect to use

 We have to tell Hibernate which attributes of player object have to be mapped with which columns of player table. These mapping definitions which are used by Hibernate to persist objects into relational database will be given in a file “player.hbm.xml”. The id element in this file is important. Each persistent class must have an id element declaring the primary key for the relational table.

We can start creating a java project that uses hibernate in Eclipse IDE. Launch Eclipse workbench. Choose in the File menu  new->project. A new project wizard will appear. Select among the choices ‘Java project” and click next. A new Java project Dialogue box will appear. In the text box “Project name” give the name hibernateconsole and  click the radio button “create separate source and output folders” and leave the default values untouched for other things and click “next “ and you will get the following:

Click Finish.
             Select the project name (hibernateconsole) in the project explorer and right click.. Choose new class and in the box that appears give name as player. You can use default values for other things but see to it that check box for main is unchecked and click Finish. You can see in the project explorer under package name default package a source file player .java was created and you complete the for the source file created by the IDE with the following: code .You can give the attributes and for methods you can use the facility for generating constructors and getters and setters under source menu or manually complete.

 

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

Again Select src folder  and right click and choose new file. In the dialogue box that appears give the File name as”hibernate.properties” and click Finish. Fill  the file with the following code.

hibernate.dialect=net.sf.hibernate.dialect.MySqlDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost/hiberdemo
hibernate.connection.username=madhan
hibernate.connection.password=madhan

Once again select src  new->file .Give the file name as player,hbm.xml. and click finish.. Complete the file with the following code:

<?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" column="id"
unsaved-value="0">
<generator class="increment" />
</id>
<property name="name" type="string" />
<property name="place" type="string" />
</class>
</hibernate-mapping>

Select hibernateconsole and repeating above steps create “commons-logging.properties” file also The code for the same is as follows:
org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog

 Now we will create the java class under the src and it will  contain the main method:. Once again select “src” .Right click. Choose new->class. In the dialogue box and give the name  as “hiberconsole” and click Finish. The IDE will create the source code.Complete the source with the following code.


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
import java.util.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

class hiberconsole
{
public static void main(String args[])
{
SessionFactory factory=null;
System.out.println ("Creating factory");
Log log = LogFactory.getLog(hiberconsole.class);
try
{
Configuration cfg =
new Configuration();
cfg.addClass(player.class);

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

}
catch(Exception e1)
{ log.error(""+e1);}

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

try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

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

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

if(s.equals("add"))
{
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));

System.out.println("What name? ");
String a = br1.readLine();
BufferedReader br2=new BufferedReader(new InputStreamReader(System.in));

System.out.println("What Place? ");
String b = br2.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)
{log.error(""+e1);}
}
//-------------------------------------

if(s.equals("remove"))
{
try
{
BufferedReader br3=new BufferedReader(new InputStreamReader(System.in));

System.out.println("What key? ");
String a = br3.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)
{log.error(""+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
{
BufferedReader br4=new BufferedReader(new InputStreamReader(System.in));

System.out.println("What key ");
String a = br4.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)
{log.error(""+e1);}

 

}
//------------------------------------------
if(s.equals("update"))
{
try
{
BufferedReader br5=new BufferedReader(new InputStreamReader(System.in));

System.out.println("What key ");
String a = br5.readLine();
Session session = factory.openSession();

 

tx = session.beginTransaction();

 

int i=Integer.parseInt(a);
player player1 = (player)session.get(player.class,new Integer(i));
BufferedReader br6=new BufferedReader(new InputStreamReader(System.in));

System.out.println("what name?");
String s1 = br6.readLine();
BufferedReader br7=new BufferedReader(new InputStreamReader(System.in));

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

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

 

}catch(Exception e1)
{log.error(""+e1);}
}
//-----------------------------------

} while(!s.equals("over"));
}
catch(Exception e1) { log.error(""+e1);}
}
}

You could see in the above code  the following:

 1) a Configuration object is created 2)the Configuration object invokes the  addClass method() 3)Configuration object invokes the buildSessionFactory method( ) and this method  returns SessionFactory object   
4) the SessionFactory object invokes the openSession method and this method returns a Session object  and only this Session object is used to begin, commit transaction and save delete etc data The session is closed with every single transaction.

The following diagram shows the various objects involved:

For the project to be built and run you have to set the build path. Before doing that copy the mysql driver to the lib sub directory of your hibernate installation.

Select hibernateconsole -> right click choose Build path ->Configure Build path. you get the following box.

Select “Libraries” tab .Select “Add External Jar” button. In the jar selection box that appears browse for the hibernate jar file of your hibernate2 installation(not hibernate3, for using hibernate3 the code needs some tweaking). Click open. Likewise once again click “Add external Jars” go to the lib sub directory of your hibernate2 installation select all jar files there and click open. You will get the following:

Now you can build the project by selecting hibernateconsole in the package explorer and right clicking and selecting Build project in the pop-up menu that appears. After the project is built select the file hiberconsole that contains the main method and right click. Choose Run As -> Java Application and click .You can see the application executing.

Note : For clarifications ,the author can be contacted. email id sekaran_madhan@yahoo.com








}