Tech Tidbits - Ruby, Ruby On Rails, Merb, .Net, Javascript, jQuery, Ajax, CSS...and other random bits and pieces.

Sunday, April 29, 2007

Hibernate 3 Tutorial

Here's a simple Hibernate tutorial which will guide you through installation, configuration, and use of Hibernate 3.2, HSQLDB, Ant, and Java on Linux...

This is a rather contrived example and nothing you would see in the real world, but I'll probably expand on this example in later posts.

You'll need the following to run this Hibernate example:

Apache Ant
Hibernate
Hibernate Tools
Hsqldb

As of April 23, 2007, these were the latest downloads:

apache-ant-1.7.0-bin.tar.gz
hibernate-3.2.2.ga.tar.gz
HibernateTools-3.2.0.beta9a.zip
hsqldb_1_8_0_7.zip

I installed these under /usr/local on my laptop (Fedora), but you can install them anywhere that works for you.

So I ended up with this directory structure:

/usr/local/apache-ant-1.7.0
/usr/local/hibernate-3.2
/usr/local/HibernateTools
/usr/local/hsqldb

Note: Manually create the HibernateTools directory and unzip the HibernateTools zip file there.

Create a project directory where you'll place your project files. I created a project directory called "Book" in my home directory (/home/doug/Book).

Here's the project file layout:


Book -
build.properties
build.xml
classes -
data -
src -
hibernate.cfg.xml
log4j.properties
com -
dougsparling -
AddBook.java
Book.hbm.xml
Book.java
ListBooks.java


Database files will build under the data directory. The classes directory will be created during the Ant build process, so you don't need to create that directory manually.

1) Ant build script


Includes targets to create schema/database tables, prepare project files and directories, and compile java source code, as well as a target to add books to the database and another target to read books from databasae.

Book/build.xml
-------------------

<?xml version="1.0"?>
<project name="book">

<!-- properties -->
<property file="build.properties"/>

<property name="src" value="src"/>
<property name="class" value="classes"/>
<property name="data" value="data"/>
<property name="hibernate.tools"
value="${hibernate.tools.home}${hibernate.tools.path}"/>

<!-- project classpath -->
<path id="project.classpath">
<pathelement location="${src}"/>
<pathelement location="${class}"/>
<pathelement location="${hibernate.home}/hibernate3.jar"/>
<fileset dir="${hibernate.home}/lib" includes="**/*.jar"/>
<pathelement location="${hsql.home}/lib/hsqldb.jar"/>
</path>

<!-- Hibernate tools classpath -->
<path id="tools.classpath">
<path refid="project.classpath"/>
<pathelement location="${hibernate.tools}/hibernate-tools.jar"/>
</path>

<!-- task def for Hibernate Tools -->
<taskdef name="htools"
classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="tools.classpath"/>

<!-- Create runtime subdirectories -->
<target name="prepare">
<mkdir dir="${class}"/>

<!-- Copy property files and O/R mappings needed at runtime -->
<copy todir="${class}">
<fileset dir="${src}">
<include name="**/*.properties"/>
<include name="**/*.cfg.xml"/>
</fileset>
</copy>
</target>

<!-- Generate schemas for all mapping files -->
<target name="schema" depends="prepare">
<htools destdir="${data}">
<classpath refid="tools.classpath"/>
<configuration
configurationfile="${src}/hibernate.cfg.xml"/>
<hbm2ddl drop="true" outputfilename="book.sql"/>
</htools>
</target>

<!-- Compile java source code -->
<target name="compile" depends="prepare">
<javac srcdir="${src}"
destdir="${class}"
debug="on"
optimize="off"
deprecation="on"
classpathref="project.classpath"/>
</target>

<!-- Add a book (create and persist) -->
<target name="addBooks" depends="compile">
<java classname="com.dougsparling.AddBook"
classpathref="project.classpath"/>
</target>

<!-- Display persisted data -->
<target name="listBooks" depends="compile">
<java classname="com.dougsparling.ListBooks"
classpathref="project.classpath"/>
</target>

</project>


2) build.properties


This file is included in the build.xml file. build.properties contains paths to the installed libraries.

Book/build.properties
-----------------------------------------

# Path to the hibernate install directory
hibernate.home=/usr/local/hibernate-3.2

# Path to the hibernate-tools install directory
hibernate.tools.home=/usr/local/HibernateTools

# Path to hibernate-tools.jar relative to hibernate.tools.home
hibernate.tools.path=
/plugins/org.hibernate.eclipse_3.2.0.beta9a/lib/tools

# Path to the HSQL DB install directory
hsql.home=/usr/local/hsqldb


3) Hibernate configuration file


Database connection information mappings.

Book/src/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-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">
jdbc:hsqldb:file:data/book;shutdown=true
</property>
<property name="hibernate.connection.driver_class">
org.hsqldb.jdbcDriver
</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">0</property>
<property name="hibernate.dialect">
org.hibernate.dialect.HSQLDialect
</property>
<property name="hibernate.show_sql">false</property>

<!-- mapping resources -->
<mapping resource="com/dougsparling/Book.hbm.xml"/>

</session-factory>
</hibernate-configuration>


4) Logging


Set up logging. You can use the file that comes in the etc directory of the HibernateTools in the unpacked archive file.

Book/src/log4j.properties

5) Book class


POJO class to represent a book

Book/src/com/dougsparling/Book.java
-----------------------------------------

package com.dougsparling;

public class Book {
private int id;
private String title;

public Book(String title) {
this.title = title;
}

Book() {
}

public int getId() {
return this.id;
}

public void setId(int id) {
this.id = id;
}

public String getTitle() {
return this.title;
}

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


6) Object mapping for Book class



Book/src/com/dougsparling/Book.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="com.dougsparling.Book" table="book">

<id name="id" type="int" column="id">
<generator class="native"/>
</id>

<property name="title" type="string"/>

</class>
</hibernate-mapping>


7) AddBook class


Code to add a book to database

Book/src/com/dougsparling/AddBook.java
--------------------------------------------

package com.dougsparling;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.dougsparling.Book;

public class AddBook {
public static void main(String[] args) {

String title = "A Book";

SessionFactory factory =
new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();

Book book = new Book(title);

session.save(book);
session.getTransaction().commit();
session.close();
}
}


8) ListBooks class


Code to read books from database

Book/src/com/dougsparling/ListBooks.java
----------------------------------------------

package com.dougsparling;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.dougsparling.Book;

public class ListBooks {
public static void main(String[] args)
{
SessionFactory factory =
new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();

List books = session.createQuery("from Book").list();
System.out.println("Found " + books.size() + " books(s):");

Iterator i = books.iterator();
while(i.hasNext()) {
Book book = (Book)i.next();
System.out.println(book.getTitle());
}

session.close();
}
}


9) Ant build


At this point it's time to run Ant against the build.xml file.


kl93@oiche:/home/kl93/Book$ ant schema
kl93@oiche:/home/kl93/Book$ ant addBooks
kl93@oiche:/home/kl93/Book$ ant listBooks

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.

Labels