Hibernate中update与merge方法对比:数据库访问时机问询
Great question—this is a super common point of confusion when working with Hibernate's session lifecycle! Let's break down exactly what happens with each method, and when database calls actually happen:
What's the Default Behavior?
By default, neither update() nor merge() triggers an immediate database write (UPDATE statement). Both rely on Hibernate's dirty checking mechanism and session flushing to sync changes to the database. But there's a key difference with merge() that can lead to an immediate read query.
Let's Start with update()
- When you call
session.update(detachedObject), Hibernate does two main things right away:- Attaches the detached object to the current session (moving it to the persistent state).
- Marks the object as dirty (meaning it has changes that need to be synced to the database).
- No SQL is sent to the database at this point. The UPDATE statement only gets executed when the session is flushed—either explicitly via
session.flush(), or automatically when the transaction is committed. - Remember: As you noted,
update()will throw an exception if there's already a persistent object with the same ID and type in the session.
Now merge()
This one has a twist, because of how it handles object state:
- When you call
session.merge(detachedObject), Hibernate first checks if there's already a persistent instance with the same ID in the current session.- If there is: It copies all the property values from your detached object to the existing persistent one, marks that persistent object as dirty, and returns it. No immediate database calls here—the UPDATE still waits for flush/commit.
- If there isn't: Hibernate will immediately execute a
SELECTquery to fetch the existing entity from the database (or create a new persistent instance if it doesn't exist). Then it copies your detached object's properties to this persistent instance, marks it as dirty.
- The critical note here:
merge()will hit the database immediately only if it needs to fetch the existing entity (when it's not already in the session cache). The subsequent UPDATE still waits for flushing.
When Does the Database Actually Get Updated?
All pending changes (from both update() and merge()) are synced to the database during a session flush. This happens automatically in two common scenarios:
- When you commit the transaction (
transaction.commit()). - When you execute a query that requires up-to-date data (Hibernate flushes to avoid stale query results).
You can also trigger it manually withsession.flush().
内容的提问来源于stack exchange,提问作者Daniel

