/ ERROR, FACTS, HIBERNATE, MISTAKE, MISUNDERSTANDING, UNDERSTANDING

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.

This is the 1st post in the Hibernate hard facts focus series.Other posts include:

  1. Hibernate hard facts part 1 (this post)
  2. Hibernate hard facts part 2
  3. Hibernate hard facts part 3
  4. Hibernate hard facts - Part 4
  5. Hibernate hard facts – Part 5
  6. Hibernate hard facts - Part 6
  7. Hibernate hard facts – Part 7

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.

You will find proof of this assertion here.

Nicolas Fränkel

Nicolas Fränkel

Nicolas Fränkel is a technologist focusing on cloud-native technologies, DevOps, CI/CD pipelines, and system observability. His focus revolves around creating technical content, delivering talks, and engaging with developer communities to promote the adoption of modern software practices. With a strong background in software, he has worked extensively with the JVM, applying his expertise across various industries. In addition to his technical work, he is the author of several books and regularly shares insights through his blog and open-source contributions.

Read More
Hibernate hard facts part 1
Share this