Database Guide : GLORP Tutorial : Detached Objects
Detached Objects
After reading an object from the database, the object can remain after the session that read it is closed. Such an object is detached from the database.
session := codeToGetASession.
[sam := session readOneOf: Person where: [:each | each firstName = ‘Sam’].
codeToCloseConnection.
There are two dangers in doing this. First, keeping an object in memory for long periods of time increases the probability that object’s data will not be consistent with the database. Another thread or client may alter the database version, and any changes in the in memory object will not be written to the database. Second, when GLORP reads an object, any references to collections and complex objects are replaced with proxies. The data is not read from the database until the proxy is actually used. The proxy holds a reference to the session used to originally read the object. This session is used to read the collection. If the session has been closed, then an exception is raised when trying to access the collection. So any method in a detached object that references a proxy collection will not work. If the session is not closed (or more accurately the underlying accessor closed), but you no longer have a reference to the session the object is not detached and the proxy will still work.
The Smalltalk expression below reattaches the object to the database by registering it with a session.
session := codeToGetASession.
session register: sam.
This should also register all nested objects inside of Sam. It is not clear if changes to sam before you register it will be saved, but any changes made after you register it will be saved.
There are situations where detached object make sense, but make sure you know what you are doing and understand your situation very well before trying this.
Last modified date: 01/29/2015