How to Handle Detached Hibernate Objects and Reattach Them
In this article
- What Are Detached Objects in Hibernate?
- How to Reattach a Detached Object
- Choosing Between update(), merge(), and saveOrUpdate()
- Common Problems with Detached Objects
- Detached Objects vs. Transient vs. Persistent
- Best Practices for Working with Detached Objects
- Alternatives to Reattaching
- Frequently Asked Questions
To handle detached objects in Hibernate, you reattach them by calling session.update(), session.merge(), or session.saveOrUpdate() on a new session, passing the detached instance. The choice depends on whether you want to force an update or merge changes with existing data. Below is a detailed explanation of detached objects, why they occur, and how to work with them safely.
What Are Detached Objects in Hibernate?
In Hibernate, an entity goes through several life-cycle states: transient (new, no ID), persistent (associated with a session), detached (previously persistent but the session was closed), and removed. A detached object still has a database identity (a primary key) but is no longer tracked by a Hibernate session. This commonly happens when you load an entity in one session, close the session, and later try to modify and save it in another session—typical in web applications where each HTTP request opens a new session.
Detached objects are not automatically synchronized with the database. If you change a detached object and do nothing, the changes are lost. To persist those changes, you must reattach the object to a new session.
How to Reattach a Detached Object
You have three primary methods to reattach a detached object, each with a different behavior:
session.update(entity)– This reattaches the entity and schedules anUPDATE. It throws an exception if another persistent instance with the same identifier already exists in the session.session.merge(entity)– This copies the state of the detached object into a persistent instance with the same ID (loading it if necessary), and returns the managed instance. It is safer when you are unsure if the entity exists in the session.session.saveOrUpdate(entity)– This either saves a transient instance or updates a detached one. It is convenient but can be ambiguous if the object has no identifier.
The typical pattern is:
- Open a new session.
- Begin a transaction.
- Call
session.update(yourDetachedObject)orsession.merge(yourDetachedObject). - Commit the transaction.
- Close the session.
Example using update():
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.update(detachedUser); // user has an ID
tx.commit();
session.close();Choosing Between update(), merge(), and saveOrUpdate()
Your choice depends on the scenario:
- Use
update()when you are certain the entity is detached and no other managed instance exists in the session. It is straightforward and throws an error if you accidentally try to update a transient object (with no ID). - Use
merge()when you are not sure if the entity is detached or transient, or when you might have a managed instance already.merge()is more forgiving: it will copy state onto an existing managed instance or create a new one. It returns the managed instance, so you should use the returned reference for further operations. - Use
saveOrUpdate()when you want Hibernate to decide between saving and updating based on the identifier. It is common in simple CRUD, but be cautious with transient objects that have an assigned ID—it may treat them as detached and issue an update instead of an insert.
In general, merge() is the safest choice for detached objects in web applications because it avoids exceptions and works well with long conversations.
Common Problems with Detached Objects
Several pitfalls can occur:
- LazyInitializationException – If you try to access a lazy-loaded collection or property after the session is closed, you get this exception. To handle it, either initialize the needed data before closing the session (e.g., by using
Hibernate.initialize()), or fetch it eagerly in the query. - NonUniqueObjectException – This occurs when you call
update()on a detached object while another persistent instance with the same ID is already in the session. Usingmerge()avoids this. - Stale data – If another transaction modifies the same row after you loaded the detached object, your update might overwrite those changes. Use optimistic locking with
@Versionto detect conflicts.
Detached Objects vs. Transient vs. Persistent
It helps to understand the lifecycle clearly:
- Transient – No ID, not associated with a session. Use
save()orpersist(). - Persistent – Has an ID and is associated with a session. Changes are automatically flushed to the database at commit time.
- Detached – Has an ID but the session is closed. Changes are not tracked until you reattach.
Detached objects are not a Hibernate-specific concept; they are a natural consequence of session-per-request patterns. Understanding the state helps you decide which method to call.
Best Practices for Working with Detached Objects
- Always use
merge()when you are working with data from a UI that may have been modified outside a session. - Consider using a session-per-request pattern with
OpenSessionInViewto avoid lazy loading issues, but be aware of the performance cost. - If you need to reattach an object with a complex graph, make sure all lazy associations are initialized before closing the session, or use
merge()which cascades appropriately if configured. - For batch updates, consider using
session.update()in a loop, but be mindful of the session cache size.
Alternatives to Reattaching
Sometimes you don't need to reattach at all. You can:
- Use native SQL or JPQL updates – For simple updates, a bulk update query like
UPDATE User u SET u.name = :name WHERE u.id = :idis efficient and avoids loading the entity. - Use DTOs – Transfer only the necessary fields to the service layer and construct a new entity with the ID, then call
merge(). - Use a stateless session –
StatelessSessionbypasses the persistence context and is useful for bulk operations, but it does not provide dirty checking or cascading.
Frequently Asked Questions
What happens if I call update() on a transient object?
If the object has no identifier, update() will throw a TransientObjectException. You should use save() or persist() for transient objects.
Can I reattach a detached object that has a lazy-loaded collection?
Yes, but you must initialize the collection before closing the session, or access it within the same session. Otherwise, you'll get a LazyInitializationException when trying to access it after reattachment.
What is the difference between update() and merge()?
update() directly reattaches the object and schedules an update, but fails if a managed instance with the same ID exists. merge() copies the state onto a managed instance (loading it if necessary) and returns that instance, making it safer in most cases.
Does merge() always perform an SQL UPDATE?
Not necessarily. If the entity is transient (no ID), merge() will insert a new row. If it is detached, it will update. If the state is unchanged, Hibernate may still issue an update, but you can use @SelectBeforeUpdate to avoid unnecessary updates.
Is it safe to use saveOrUpdate() for detached objects?
It is generally safe, but be cautious with assigned identifiers. If you have a transient object with an ID, saveOrUpdate() might treat it as detached and update a non-existent row. In such cases, use save() explicitly.