Sunday, February 21, 2010

Hibernate hard facts

Hibernate is a widely-used ORM framework. Many organizations use it across their projects in order to manage their data access tier. Yet, many developers working on Hibernate don’t fully understand the full measure of its features. In this serie of articles, I will try to dispel some common misunderstandings regarding Hibernate.
Updating a persistent object

A widely made mistake using Hibernate is to call the update() method on an already persistent object :

session.getTransaction().begin();
Person person = (Person) session.load(Person.class, 1L);
person.setLastName("FooBar");
session.update(person);
session.getTransaction().commit();


This will get you the following Hibernate outputs :

Hibernate: select person0_.id as id0_0_,
   person0_.birthDate as birthDate0_0_,
   person0_.FIRST_NAME as FIRST3_0_0_,
   person0_.LAST_NAME as LAST4_0_0_ from Person person0_ where person0_.id=?
Hibernate: update Person set birthDate=?, FIRST_NAME=?, LAST_NAME=? where id=?

Now remove the line numbered 7. You get exactly the same output! If you check the database, the result will be the same: calling update() does nothing since the object is already persistent. If you are in debug mode, you can even check that the output’s update line is called when commiting the transaction in both cases.

Read more: Part 1: Updating a persistent object,  Part 2: Directional associations,  Part 3: Custom type mapping,  Part 4: Between get() and load() methods

Posted via email from jasper22's posterous