Wednesday, July 9, 2008

What is Hibernate? What is Java Persistence with Hibernate? Understanding ORM with Hibernate3...

What is Hibernate3 all about? Why use Hibernate for Object Relational Mapping?

To see the original webpage from which this blog post originates, head over to

What is Hibernate, you ask?

Well, there's a long answers to that, and there's short answers to that. The short and simple answer? Hibernate makes it easy to save data to, or load data from, a database.

And of course, Hibernate is Java based, and we all love Java. Java's object oriented, it's cross platform, it's fun to code, and it makes you think of that black blood of the soul: Tim Hortons Coffee. Seriously though, Hibernate is real easy to use, especially if you have a bit of a Java background. And it integrates quite naturally into your existing Java programs.

I keep hearing the term 'Java Persistence.' What does 'Java Persistence' mean?

When we write Java code, we create objects, and those objects have properties. Here's a simple piece of code. Just by looking at it, I think you can tell what the User's name and password are:

User user = new User();        //an object named user is created
user.setName("Cameron"); //name is initialized to Cameron
user.setPassword("n0tte11ing");//password is initialized to n0tte11ing

I think even the uninitiated Java programmer would recognize that we have just created a user named Cameron with a password of n0tte11ing. We see this type of object creation and property initialization in Java programs all the time. But the problem Java developers always have is figuring out how to take the data associated with the object and save it to the database. Hibernate makes the persistence of your Java objects, aka Java Persistence, easy.

Just how easy is it to persist Java objects with Hibernate?

With a magical and mystical object known as the Hibernate Session, persisting the state of your Java objects is easy. Look how readable and understandable the following code is:

User user = new User();        //an object named user is created
user.setName("Cameron"); //name is initialized to Cameron
user.setPassword("n0tte11ing");//password is initialized to n0tte11ing
Session hibernateSession = HibernateUtil.getSession();
//get the magical Hibernate session; //save the user to the database!

The line of code; saves the state of the user instance to the database. Of course, there's a little bit of plumbing code that needs to go in there to make the whole hibernate framework work; But setting up that plumbing code really isn't that bad. Overall, Hibernate is real easy to use, fairly easy to set up, and probably the easiest way to manage the persistent state of you domain model objects.

What are JPA Annotations?
Explaining why JPA annotations are better than crummy hbm mapping files...

JPA annotations greatly simplify persistence programming with Hibernate, but to understand why they're so great, it helps to understand what we needed to do before the introduction of annotations.

Back to the Future: This Historical hibernate-mapping.xml File

Hibernate makes persisting the state of your Java objects incredibly simple. However, in order for Hibernate to know where to story your JavaBeans, or how to map the property of a JavaBean to a database column, the developer has to provide a bit of direction to the Hibernate framework. As such, people developing Hibernate based applications had to maintain an unweildly, monolithic mapping file that described how to save a given Java object to the database.

So, for example, if you had a class named Event that had three properties, one called id, one called birthday, and another property called title, you would have to add the following segment to a hibernate-mapping file:

(won't show because blogger is messing up the < and &gt tags.)


What's wrong with an XML mapping file?

There is nothing inherently wrong, with a mapping file, and in fact, thousands of very salacious hibernate applications that are in production use an XML mappings file, but having a big XML mapping file presents a variety of non-lethal, but certainly annoying problems, including the following:

  • information about the Java class must be maintained in an external file
  • XML isn't always easy to write
  • with lots of classes, the XML file can become unweildly and massive
  • errors in one part of the XML file can ricochet all over your Java program

Anyways, Java 5 introducted a new Java based artifact - that annotation. Basically, an annotation allows you to add detail an information about a Java class, without damaging, disturbing or changing any of the code that is actually found inside a Java class or a Java method. So, instead of using a monolithic mappings file, Hibernate with JPA annotations allows you to completely rid applications of a mapping file, and instead, you can annotate your Java classes like so:

public class Event {
private Long id;
private String title;
private Date date;
public Long getId() { return id; }
private void setId(Long id) { = id;}
public Date getDate() {return date;}
public void setDate(Date date) { = date;}
public String getTitle() {return title;}
public void setTitle(String title) {this.title = title;}

The @Entity, @Id and @GeneratedValue tags you see in the Event class are the JPA annotations, and they replace the neeed to describe how to persist your Java classes in an external hibernate-mappings.xml file. Instead of using an external file, each Java class maintains its own mapping information, which is much more natural, and much easier to maintain on a class by class basis. Furthermore, it makes introducing new classes, or even removing persistent classes from your domain model, much much easier.

If you're using Hibernate, and you have the ability to choose between using annotations or using a hibernate-mapping file, well, it's really not much of a choice. Always use JPA annotations if you have a choice. JPA annotations are much easier to use, easy to maintain, and will help to make your Hibernate development experience a real pleasure. :)

To see the original webpage from which this blog post originates, head over to

java spring cache class collection configuration database dialect download example mapping query sql tutorial xml struts xp 3 3.0 api caching cfg xml dao examples framework generator in action jdbc list one to one plugin properties tool tools training tutorials java persistence with jboss linux standby ubuntu xdoclet synchronizer computer disable enable 2 3.2 annotation annotations bag batch blob button c3p0 cascade command composite id composite key config connection criteria date delete discriminator documentation ehcache entitymanager enum fetch file filter flush formula forum hbm hbm2ddl hbm2ddl auto hql id in vista inheritance insert interceptor interview questions inverse javadoc join jpa lazy lazy loading load logging many to many many to one map mapping file merge mode named query order order by org performance problems property proxy query language reference restrictions reverse engineering save saveorupdate search select sequence session sessionfactory set shortcut show_sql source sql query stored procedure template timestamp transaction type update usertype validator version how to laptop net sf netbeans org dialect org session sleep sleep vs spring and standby vs turn off vista what is windows windows xp all 150 Help java spring apache xml ajax cache cmp j2ee s truts tomcat ejb jboss jsf maven primary key ruby on rails foreign key hibernation ibatis one to one spring framework xdoclet hql hybernate jdo many to many middlegen ojb one to many

No comments: