How is it possible for the detached entity to be a persistent object in hibernate?

200 views Asked by At

I read about Transient, Persistent and Detached. It seems most part is straight forward to understand. What I am not able to get over is, when we use session.close() the entity objects that are already in first level cache gets deleted or cleared and in my view there is no chance to bring or put back the entity or object to persistent state. But then I see or read from different source is that, detached entity can still be reattached to a new session at later though. How is it possible when first level cache is cleared after doing session close?

1

There are 1 answers

0
Radim Köhler On

I'd like to assure you, that this is not so complicated. Simply...

  • we can load an entity in one session (session instance) - and close such session while keep reference to loaded entity. That entity will become detached, once the session is closed
  • we can open new session (different session instance) - and re-attach that entity. We are then able to persist changes made meanwhile.

That's it. More details from doc:

11.6. Modifying detached objects

Many applications need to retrieve an object in one transaction, send it to the UI layer for manipulation, then save the changes in a new transaction. Applications that use this kind of approach in a high-concurrency environment usually use versioned data to ensure isolation for the "long" unit of work.

...

Use update() if you are certain that the session does not contain an already persistent instance with the same identifier. Use merge() if you want to merge your modifications at any time without consideration of the state of the session.

So, the point here is ... the entity loaded with session is not transient. It is persisted already. It becomes detached once session is closed. But could be re-atteched later, to another session