Hibernate Study

 

1. Configuring Hibernate

Hibernate can be configured by creating a property file named hibernate.properties in the src directory and adding its path to the application's classpath. This file consists of the properties used by Hibernate to connect to database, generate schema, and obtain other database-specific information. To reflect changes in the underlying database into the whole application, only values of the properties in this file need to be modified. Listing 1 shows a simple example. Most of these properties are self-explanatory.

Listing 1: A simplel example of hibernate.properties file

hibernate.connection.driver_class = COM.ibm.db2.jdbc.app.DB2Driver
hibernate.connection.url = jdbc:db2:inventory
hibernate.connection.username = db2admin
hibernate.connection.password = rafel
hibernate.dialect = cirrus.hibernate.sql.DB2Dialect

 

Note: Now Hibernate also can be configured by using a simple XML file named hibernate.cfg.xml, which exists inside the src directory. This file's structure is very similar to hibernate.properties and has the same functionality. Listing 2 gives an example.
Listing 2: Example of  a simple hibernate.cfg.xml
 
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 2.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration>

    <session-factory>
        <property name="hibernate.connection.driver_class">COM.ibm.db2.jdbc.app.DB2Driver</property>
        <property name="hibernate.connection.url">jdbc:db2:empl</property>
        <property name="hibernate.connection.username">db2admin</property>
        <property name="hibernate.connection.password">rafel</property>
        <property name="dialect">cirrus.hibernate.sql.DB2Dialect</property>
     

        <mapping resource="com/myPackage/myApplication/data/Event.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

2. Building an Application with Hibernate

Now, we are ready to build the application. For that, the following steps need to be taken.

  • Creating mapping documents
  • Generating stub Java classes for persistent objects
  • Generating database schema
  • Preparing code to initialize and run Hibernate in an appropriate place

These steps are explained in the following sections.

Creating Mapping Documents

Mapping documents are XML documents used to define the persistent objects and contain information about an object's persistent fields, associations, subclasses, and proxies, if any. One mapping document is created for each persistent object and saved in a file with the name class_name.hbm.xml, where class_name is the name of the object's class. Listing 3 gives an example of mapping document Event.hbm.xml.

The mapping documents are compiled at application start-up to provide Hibernate with information about the persistent objects' corresponding classes, their respective structures, to which database table should they be mapped, and how. Hibernate also uses these mapping documents to generate corresponding database schema and stub Java classes for the persistence layer, using inbuilt utilities called SchemaExport and CodeGenerator, respectively.

 

Listing 3 : An example of mapping document Event.hbm.xml


<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>

        <class name="com.myPackage.myApplication.Event" table="EVENTS">
                <id name="id" column="uid" type="long">
                        <generator class="increment"/>
                </id>
                <property name="date" column="event_date" type="timestamp"/>
                <property name="title" column="event_title" type="string"/>
        </class>

</hibernate-mapping>

 

Generating Stub Classes

This task becomes simpler after mapping documents are created. Stub classes can be created by using Hibernate's built-in utility CodeGenerator by executing a simple command. Command's syntax is given below:

java -cp classpath net.sf.hibernate.tool.hbm2java.CodeGenerator
         options mapping_files

Provide appropriate values for the classpath, options, and mapping_files parameters. Listing 4 shows the stub file generated using the mapping document given in Listing 3.

Listing 4 Stub Classes
package com.myPackage.myApplication;

public class Event {
    private String title;
    private Date date;
    private Long id;

    Event(){ }

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Generating Database Schema

To generate database schema using Hibernate's SchemaExport, execute the following command after substituting appropriate values for parameters:

java -cp classpath net.sf.hibernate.tool.hbm2ddl.SchemaExport
         options mapping_files

Provide appropriate values for the classpath, options, and mapping_files parameters. Figure 1 shows the schema generated using the mapping document given in Listing 3.

Figure 1: Graphical representation of schema generated using the mapping document in Listing 3

 

Initializing and Running Hibernate

To initialize and run hibernate, the following steps are to be taken:

  • Inside an appropriate class, instantiate and populate the desired object to be persisted.
  • Obtain the net.sf.hibernate.SessionFactory object using the net.sf.hibernate.cfg.Configuration object at the start of the application.
  • Open net.sf.hibernate.Session by calling the openSession() method on the SessionFactory object.
  • Save the desired object and close the Session.

Listing 5 shows how to implement the steps described above using a simple class. Now, the application is complete and, when executed, saves the desired objects to the underlying database, i.e. makes them persistent.

   
Listing 5: A simple class for initializing Hibernate and making objects persistent.

package com.myPackage.myApplication;

import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;

public class EventManager {

  public static void main(String[] args) {
	
        // Instantiate and populate object to be persisted
        Event ev = new Event();
        ev.setDate("1/4/2004")
        ev.setTitle("Hibernate startup");

 
        try {
           //Start Hibernate
        Configuration cfg = new Configuration().addClass(Event.class);
        SessionFactory sf = cfg.buildSessionFactory();

        //Open Session
        Session sess = sf.openSession();

        } catch (HibernateException e) {
            e.printStackTrace();
        }

        //Save Product and close Session
        Transaction t = sess.beginTransaction();
        sess.save(ev);
        t.commit();
        sess.close();
   
    }

}
 

Conclusion

Hibernate is a powerful, high-performance, feature-rich and very popular ORM solution for Java. Hibernate facilitates development of persistent objects based on the common Java object model to mirror the underlying database structure. Along with mapping objects to a database, Hibernate also provides advanced data query and retrieval services through HQL, efficient caching, and other optimization techniques and useful built-in utilities for code and schema generation.

By automating the generation of a persistence layer to a large extent, Hibernate helps relieve the developer of up to 95% of common persistence-related coding.

 

Modifies from www.developer.com/java/ent/article.php/3312051

O/R Mapping with Hibernate
By Mugdha Chauhan
February 12, 2004