The reason to not close a session, is to ensure the objects that are retrieved from the session are not detached.
Plus if we do not want to use "Open session pattern", we have to deal with reataching a detached object:
- Which object need to be attached if it has parent-child relationship?
We need to ensure cascade property is set up correctly and care must be taken when dealing with unidirectional object. I.e. A has getB() but B does not have getA(). This mean re-attach B does not make A to be persistent.
- How to reattach a detached object without causing any modified fields to be persisted upon transaction commit?
1. session.refresh() refresh the detached object from the database and make it persistent (Any modified fields will be refreshed);
2. session.update() causes the detached object to be persistent object and upon transaction commit, the database will be updated;
3. session.merge(), merge the changes, BUT, it is unclear whether it will update the database upon transaction commit and whether we can navigate the object graph.
Quote:
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge".
The semantics of this method are defined by JSR-220.
Basically it says that the detached object will be
persistent but
not associated to the current session?
Does not persistent means:
Quote:
persistent: associated with a unique Session
Note: This is taken from
http://www.hibernate.org/hib_docs/v3/ap ... ang.Object)
http://www.hibernate.org/hib_docs/v3/ap ... ssion.html
IMHO, Open Session In View pattern is
required instead of
recommended for long conversation, or at least until the javadoc is updated.
There is a danger having a session opened for long period of time. The memory usage will keep increasing, because the object is never detached from the session. This means, session.evict() need to be called, or close and create a new session when it is clear to do so.
http://www.hibernate.org/hib_docs/v3/ap ... ang.Object)
And lastly, Session.disconnect() is required to free up jdbc connection to be used by other Thread.
Regards,
Edward