Monday, April 28, 2008

Hibernate with sample application

Step1:

Download the Hibernate distribution from the Hibernate website. Extract the package and place all required libraries found in /lib into into the /lib directory of your new development working directory.

Step2: Writing POJO

Our first persistent class is a simple JavaBean class with some properties:

package events;
import java.util.Date;
public class Event {
private Long id;
private String title;
private Date date;
public 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;
}
}

You can see that this class uses standard JavaBean naming conventions for property getter and setter methods, as well as private visibility for the fields
Place this Java source file in a directory called src/Events in the development folder.

Step3: Mapping File












Just as with the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use. So, in this case, Hibernate will look for getDate()/setDate(), as well as getTitle()/setTitle().

This mapping file should be saved as Event.hbm.xml, right in the directory next to the Event Java class source file.

Step4: Hibernate Configuration File


"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">






org.hsqldb.jdbcDriver
jdbc:hsqldb:hsql://localhost
sa



1


org.hibernate.dialect.HSQLDialect


thread


org.hibernate.cache.NoCacheProvider


true


create







We configure Hibernate's SessionFactory - a global factory responsible for a particular database. If you have several databases, use several configurations, usually in several configuration files (for easier startup).

The first four property elements contain the necessary configuration for the JDBC connection. The dialect property element specifies the particular SQL variant Hibernate generates. Hibernate's automatic session management for persistence contexts will come in handy as you will soon see. The hbm2ddl.auto option turns on automatic generation of database schemas - directly into the database. This can of course also be turned off (by removing the config option) or redirected to a file with the help of the SchemaExport Ant task. Finally, we add the mapping file(s) for persistent classes to the configuration.

Copy this file into the source directory, so it will end up in the root of the classpath. Hibernate automatically looks for a file called hibernate.cfg.xml in the root of the classpath, on startup.

Step5 :building with Ant



















destdir="${targetdir}"
classpathref="libraries"/>












Run the build file C:\hibernateTutorial\>ant


Step6 :
create a HibernateUtil helper class which takes care of startup and makes accessing a SessionFactory convenient. Let's have a look at the implementation:

package util;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

}
This class does not only produce the global SessionFactory in its static initializer (called once by the JVM when the class is loaded), but also hides the fact that it uses a static singleton. It might as well lookup the SessionFactory from JNDI in an application server.

Step7: Loading and storing objects


Finally, we can use Hibernate to load and store objects. We write an EventManager class with a main() method:

package events;
import org.hibernate.Session;

import java.util.Date;

import util.HibernateUtil;

public class EventManager {

public static void main(String[] args) {
EventManager mgr = new EventManager();

if (args[0].equals("store")) {
mgr.createAndStoreEvent("My Event", new Date());
}

HibernateUtil.getSessionFactory().close();
}

private void createAndStoreEvent(String title, Date theDate) {

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();

Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);

session.save(theEvent);

session.getTransaction().commit();
}

}
We create a new Event object, and hand it over to Hibernate. Hibernate now takes care of the SQL and executes INSERTs on the database. Let's have a look at the Session and Transaction-handling code before we run this.



add a new listEvents() method:

private List listEvents() {

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();

List result = session.createQuery("from Event").list();

session.getTransaction().commit();

return result;
}

No comments: