Understanding persist followed by setter method

Why does hibernate executes an INSERT followed by UPDATE in below code?

 entityManager.getTransaction().begin();
      Employee e=new Employee();
      e.setId(12);
      e.setName("employee_12");
      e.setAge(26);
      entityManager.persist(e);
      e.setName("employee_12_modified");

        entityManager.getTransaction().commit();

Output:-

Hibernate: 
    insert 
    into
        Employee
        (age, name, id) 
    values
        (?, ?, ?)
Hibernate: 
    update
        Employee 
    set
        age=?,
        name=? 
    where
        id=?

Why doesnt’ hibernate just send an INSERT query with the new value of employee name when context is flushed? Why the need of update?

Because the persist operation creates an EntityInsertAction based on the state at the insert time and the auto-flush at commit time creates an EntityUpdateAction with the state at that time. In theory, Hibernate ORM could try to merge these two actions, but this is such an uncommon scenario that nobody cared to put time and effort into this matter.

1 Like

I get it now.Thanks a lot!