Friday 24 May 2013

Understanding Hibernate O/R Mapping


In the last example we created contact.hbm.xml to map Contact Object to the Contact table in the database. Now let's understand the each component of the mapping file.
To recall here is the content of contact.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>
  </id>

  <property name="firstName">
   <column name="FIRSTNAME" />
  </property>
  <property name="lastName">
  <column name="LASTNAME"/>
  </property>
  <property name="email">
  <column name="EMAIL"/>
  </property>
 </class>
</hibernate-mapping>

Hibernate mapping documents are simple xml documents. Here are important elements of the mapping file:.
  1. <hibernate-mapping> element
    The first or root element of hibernate mapping document is <hibernate-mapping> element. Between the <hibernate-mapping> tag class element(s) are present.
     
  2.  <class> element
    The <Class> element maps the class object with corresponding entity in the database. It also tells what table in the database has to access and what column in that table it should use. Within one <hibernate-mapping> element, several <class> mappings are possible.
      
  3.  <id> element
    The <id> element in unique identifier to identify and object. In fact <id> element map with the primary key of the table. In our code :
    <id name="id" type="long" column="ID" >
    primary key maps to the ID field of the table CONTACT. The attributes of the id element are:
    • name: The property name used by the persistent class.
    • column: The column used to store the primary key value.
    • type: The Java data type used.
    • unsaved-value: This is the value used to determine if a class has been made persistent. If the value of the id attribute is null, then it means that this object has not been persisted.
        
  4. <generator> element
    The <generator> method is used to generate the primary key for the new record. Here is some of the commonly used generators :

    * Increment - This is used to generate primary keys of type long, short or int that are unique only. It should not be used in the clustered deployment environment.

    *  Sequence - Hibernate can also use the sequences to generate the primary key. It can be used with DB2, PostgreSQL, Oracle, SAP DB databases.

    * Assigned - Assigned method is used when application code generates the primary key. 
  5. <property> element :The property elements define standard Java attributes and their mapping into database schema. The property element supports the column child element to specify additional properties, such as the index name on a column or a specific column type.



1. Understanding Hibernate <generator> element

1.     In this lesson you will learn about hibernate <generator> method in detail. Hibernate generator element generates the primary key for new record. There are many options provided by the generator method to be used in different situations.
2.     The <generator> element
3.     This is the optional element under <id> element. The <generator> element is used to specify the class name to be used to generate the primary key for new record while saving a new record. The <param> element is used to pass the parameter (s) to the  class. Here is the example of generator element from our first application:
<generator class="assigned"/>
In this case <generator> element do not generate the primary key and it is required to set the primary key value before calling save() method.
4.     Here are the list of some commonly used generators in hibernate:
Generator
Description
increment
It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
identity
It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence
The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
hilo
The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.
seqhilo
The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid
The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.
guid
It uses a database-generated GUID string on MS SQL Server and MySQL.
native
It picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned
lets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.
select
retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.
foreign
uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.





2.Using Hibernate <generator> to generate id incrementally

As we have seen in the last section that the increment class generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. In this lesson I will show you how to write running program to demonstrate it. You should not use this method to generate the primary key in case of clustured environment.

In this we will create a new table in database, add mappings in the contact.hbm.xml file, develop the POJO class (Book.java), write the program to test it out.
Create Table in the mysql database:

User the following sql statement to create a new table in the database.


 CREATE TABLE `book` (
`id` int(11) NOT NULL default '0',
`bookname` varchar(50) default NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM 

Developing POJO Class (Book.java)
Book.java is our POJO class which is to be persisted to the database table "book".
/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Java Class to map to the database Book table
 */
package roseindia.tutorial.hibernate;


public class Book {
  private long lngBookId;
  private String strBookName;
  
  /**
 @return Returns the lngBookId.
 */
  public long getLngBookId() {
  return lngBookId;
  }
  /**
 @param lngBookId The lngBookId to set.
 */
  public void setLngBookId(long lngBookId) {
  this.lngBookId = lngBookId;
  }
  /**
 @return Returns the strBookName.
 */
  public String getStrBookName() {
  return strBookName;
  }
  /**
 @param strBookName The strBookName to set.
 */
  public void setStrBookName(String strBookName) {
  this.strBookName = strBookName;
  }
}
Adding Mapping entries to contact.hbm.xml
Add the following mapping code into the contact.hbm.xml file
<class name="roseindia.tutorial.hibernate.Book" table="book">
   <id name="lngBookId" type="long" column="id" >
  <generator class="increment"/>
   </id>

  <property name="strBookName">
   <column name="bookname" />
   </property>
</class>
 Note that we have used increment for the generator class. *After adding the entries to the xml file copy it to the bin directory of your hibernate eclipse project(this step is required if you are using eclipse).
Write the client program and test it out
Here is the code of our client program to test the application.
/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Example to show the increment 
class of hibernate 
generator element to 
 * automatically generate 
the primay key
 */
package roseindia.tutorial.hibernate;

//Hibernate Imports
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class IdIncrementExample {
  public static void main
(String[] args) {
  Session session = null;

  try{
  // This step will read 
hibernate.cfg.xml and 
prepare hibernate for use
  SessionFactory sessionFactory = 
new Configuration().configure()
.buildSessionFactory();
  session =sessionFactory.openSession();
 
  org.hibernate.Transaction tx = 
session.beginTransaction();
 
  //Create new instance 
of Contact and set values in
 it by reading them from form object
 System.out.println("
Inserting Book object 
into database..");
  Book book = new Book();
  book.setStrBookName("Hibernate 
Tutorial");
  session.save(book);
  System.out.println("Book object 
persisted to the database.");
  tx.commit();
  session.flush();
  session.close();
  }catch(Exception e){
  System.out.println(e.getMessage());
  }finally{
  }
  
  }
}
To test the program Select Run->Run As -> Java Application from the eclipse menu bar. This will create a new record into the book table.

No comments:

Post a Comment

Simple CRUD in Laravel Framework

Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using reso...