Hibernate hard facts part 1

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 series 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 :

Person person = (Person) session.load(Person.class, 1L);

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.

You will find proof of this assertion here.

Nicolas Fränkel

Nicolas Fränkel

Nicolas Fränkel is a Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Currently working for Exoscale. Also double as a teacher in universities and higher education schools, a trainer and triples as a book author.

Read More