There are two main ways to update an object in Hibernate, depending on whether the object is still persistent or has become detached:
🔹 1) Updating a persistent object (easiest case)
- If the entity is still attached to an open session (persistent), simply modify its fields — Hibernate’s dirty checking will detect the changes and automatically generate the SQL
UPDATE
onflush()
orcommit()
.
Example:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = session.get(User.class, 1L); // user is now persistent
user.setEmail("newemail@example.com"); // modify persistent object
tx.commit(); // flushes changes → SQL UPDATE
session.close();
✅ Here you don’t need to call update() — Hibernate tracks changes automatically!
🔹 2) Updating a detached object
- If the entity was loaded in a previous session but is now detached (e.g., session was closed), you must reattach it to a new session using either:
session.update(entity)
→ reattaches the entity → Hibernate will update its state in the database.session.merge(entity)
→ copies the state of the detached object into a managed persistent instance, and returns it.
Example with update()
:
// Detached object (e.g., loaded before, session closed)
User detachedUser = new User();
detachedUser.setId(1L);
detachedUser.setEmail("updatedemail@example.com");
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.update(detachedUser); // reattaches → schedules UPDATE
tx.commit();
session.close();
Example with merge()
:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User managedUser = (User) session.merge(detachedUser); // returns persistent copy
tx.commit();
session.close();
🔹 Which to use — update vs. merge?
✅ update()
→ works only if there’s no persistent instance with the same ID already in the session (else throws NonUniqueObjectException
).
✅ merge()
→ safer in complex scenarios because it copies the state and returns a new managed object → avoids duplicate issues.
✅ Key takeaway:
- Persistent object? Modify fields directly → Hibernate auto-updates.
- Detached object? Reattach with
update()
ormerge()
→ then commit the transaction.