Getting started with hibernate

Getting started with hibernate - A really quick introduction by Calvin Austin

If you haven't heard of Hibernate before and are accessing a database you are either using raw jdbc calls in your application, or using another type of persistence mechanism. This short article is designed to get anyone up and running with hibernate. If something still doesn't work for you then post your error and we'll try to get it resolved.

The concept behind hibernate isn't especially new, Java based databases had a similar aim and many Java developers aim to separate data from business logic, which then in turn results in creating your own data persistence library before you know it.

Hibernate is an ORM solution, that means that you can work with your objects as normal as Plain Old Java Object (POJO). In addition hibernate can even generate all the jdbc/sql calls for you.

In this example I'm going to show you how quick and easy using Hibernate is. To make my task even faster I'm going to use the Spikesource core stack. Hibernate 2.1.8 is pre-installed with mysql if you select the Web Container stack.

Contents

Edit

Beginning

This example uses the ant build system as there are many jar files, hibernate uses over 30 of them. The ant build.xml file contains the necessary build targets and mysql integration for a newly installed SpikeSource stack. If you want to start looking at the code you can download it from here.


Edit

Hibernate Configuration

Configuring Hibernate can be achieved in a number of different ways. It can be done programatically, or using a hibernate.properties file or a hibernate.cfg.xml file. This example uses the XML hibernate.cfg.xml format and includes a database mapping. If you haven't changed anything in the Web Container install you shouldn't need to change anything.


Edit

Database Mapping

This example uses a hbm.xml mapping file, called Registration.hbm.xml to create the database entries. The naming is just a convention as the filename is passed as one of the arguments to the hbm2java tool in the build.xml file.

This file details the mapping between Java and the SQL database, this is just one of the techniques to map your Java application to the database, other options are javadoc annotations, and writing the mapping by hand.

A quick peek at this file shows how simple it is to add hibernate support using code generator tools. The table in this example is called Registration which maps to a Java Object also called Registration. Both the Registration class and Registration database table do not exist at this point.

File: Registration.hbm.xml

 <hibernate-mapping>
   <class name="Registration" table="Registration">
       <id name="id" type="long" unsaved-value="null" >
            <column name="uid" not-null="true"/>             
            <generator class="identity"/>         
       </id>
 
       <property name="first_name" type="string">
            <column name="first_name" sql-type="varchar(32)" not-null="true"/>
       </property> 
       <property name="last_name" type="string">
            <column name="last_name" sql-type="varchar(32)" not-null="true"/>
       </property>
 
       <property name="email" type="string">
            <column name="email" sql-type="varchar(80)" not-null="true"/>
       </property>
 
       <property name="subscribe" type="boolean"/>
   </class>
 </hibernate-mapping>

The Registration class has fields first_name, last_name, email and an email subscribe field. The hbm2java code generator creates accessor methods, eg getFirst_name(), to get the field first_name, setEmail() to set the email field and generates the appropriate database definitions as well. Note that the tool capitalizes the first letter in the field name and in the case of a boolean field generates the methods isSubscribe() and setSubscribe().

One special field in this examples Registration.hbm.xml file is the ID field, this is used as the primary key and can be generated by a number of rules or left to you to implement. I chose a simple identity rule that means the key value is generated from MySQL as an auto-increment or identity value.

 <id name="id" type="long" unsaved-value="null" >
            <column name="uid" not-null="true"/>
            <generator class="identity"/>
 </id>


Edit

Generating the Mapping

By using the build targets ant createdb, this generates the java file generated/Registration.java

 # ant createdb
 Buildfile: build.xml
 
 codegen:
 
 init:
    [mkdir] Created dir: /root/samples/build
 
 compile-generated:
    [javac] Compiling 1 source file to /root/samples/build
 
 cp-config:
     [copy] Copying 2 files to /root/samples/build
 
 createdb:
 [schemaexport] drop table if exists Registration
 [schemaexport] create table Registration (
 [schemaexport]    uid bigint not null auto_increment,
 [schemaexport]    first_name varchar(32) not null,
 [schemaexport]    last_name varchar(32) not null,
 [schemaexport]    email varchar(80) not null,
 [schemaexport]    subscribe bit,
 [schemaexport]    primary key (uid)
 [schemaexport] )
 
 BUILD SUCCESSFUL
 Total time: 9 seconds


Edit

Using Hibernate

Hibernate is enabled by opening a Hibernate session. A session is retrieved by a calling openSession() from a hibernate session factory. When finished with the session the close() session is called. This common code is available in HibernateUtil.java and exposed through this examples HibernateUtil class.

The source file RegisterAccount.java creates an entry in the Registration database. The key methods are the retrieval of the session through our convenience method currentSession() from HibernateUtil. Once the Object has been created we can persist it by using the save() method from the session. To write the call through we need to call the flush() method before closing the session().

The second part of this example is the source file UpdateAccount.java which then retrieves the persisted value from RegisterAccount and updates it. There are several ways we can retrieve our persisted value, One is to reference the value by primary key, another is to use a raw select statement and another is to use the hibernate selection syntax. Once selected, the Object is returned and updated. The session update method and then flush call makes the change persist.

 List<Registration> users = hsession.find("from Registration 
         as Registration where email=?", email, Hibernate.STRING);
 for (Registration changeuser : users) {
     System.out.println("Updating "+changeuser.getFirst_name()+" "
                 +changeuser.getLast_name()+" "+email+" subscription to "+  
                    !changeuser.isSubscribe());
     changeuser.setSubscribe(!changeuser.isSubscribe());
     hsession.update(changeuser);
     System.out.println("Changed User "+changeuser.getEmail());
 }
 hsession.flush();
 hsession.close();

To run the example just use the targets ant register and ant update.

 # ant register 
 Buildfile: build.xml
 
 init:
 
 compile:
    [javac] Compiling 1 source file to /root/samples/build
    [javac] Note: /root/samples/UpdateAccount.java uses unchecked or
              unsafe operations.
    [javac] Note: Recompile with -Xlint:unchecked for details.
 
 register:
 
 BUILD SUCCESSFUL
 Total time: 16 seconds

So you may be wondering, what is that unchecked operation? Well the version of hibernate I used was 1.4 based but I wanted to use the 5.0 generics. The compiler is telling me that it can't guarantee that even though I'm using Generics it can't guarantee the assignment I did from the find() method that just returned List.


Edit

Summary

That's all there is for this simple example. To learn more about Hibernate then the following resources are great additional resources.

Hibernate reference documentation and tutorial: hibernate.org

Download this example code hibernatestarted.zip



Most Recent

Most Popular

Most Active Categories


Problems with Hibernate?

Problems with Hibernate? You can post them here


Back To Top Add New Article Printable Page
MediaWiki

This page has been accessed 17,924 times.

This page was last modified 23:54, 19 June 2006.