0

I just wonder how Hibernate identifies if an object is a detached entity. I am not asking for any specific method, just want to understand the mechanism behind.

  • Basically, each session has an IdentityHashMap containing all the entities in that session. – JB Nizet Nov 22 '16 at 00:26
  • I'm not sure this is a good question. On StackOverflow you're supposed to demonstrate that you made some effort to find out yourself. The only way to answer to this question is to read Hibernate's source code to find out exactly how they did it. Any one of us could _guess_ or say how _we would do it_, but no one will know the answer without reading the source code. Have you tried to find out yourself in the source code, Tuan? If so, how far did you get? JB Nizet is right, of course, that's probably how they did it, or maybe JB Nizet is a Hibernate dev and that's exactly how they did it. – DavidS Nov 22 '16 at 00:28
  • 1
    I'm not a Hibernate dev, and I looked in the source code. – JB Nizet Nov 22 '16 at 00:40

1 Answers1

1

From JBoss Docs:

Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

So Hibernate basically keeps track of the sessions and attached objects. Any object that is associated with that session for persistence becomes detached and becomes like any other POJO.

So what Hibernate does is:

  1. Calls session.evict() on the object reference or session.clear() which removes an object from session.
  2. Hibernates persistent manager relies on the existence of an identifier to determine the state of an object. If an object has an identifier, then the object is Persistent, If it does not belong to a session then it is DETACHED.
  3. Detached objects can be reassociated and synchronized to the database after a new session is opened.
  4. Calling session.update() or session.saveOrUpdate() on a Detached object reference transitions the Detached object back to the Persistent state.
  5. When a Detached object is reattached the database is updated with object’s current state; to include changes made while it was in detached state.

A good reference can be found here.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108