Hibernate Performing the usual DB operations

This page discusses - Hibernate Performing the usual DB operations

Hibernate Performing the usual DB operations

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.
====
In part-3 of the tutorial, we will see full code and implementation for a console application as well as for a servlet.