blob: fe303436c86d75ec225ad9406e5e33cec6daba42 [file] [log] [blame]
Title: Moving Objects Between Contexts
<H2><A name="MovingObjectsBetweenContexts-MovingObjectsBetweenContexts"></A>Moving Objects Between Contexts</H2>
<P>Each instance of a DataObject belongs to only one DataContext for the duration of the object lifecycle. Sometimes there maybe a need to transfer a list of objects from one DataContext to another. The goal of this operation is to be able to use such objects in relationships with objects of the target DataContext. Most common use for this feature is the following. An application may have a &quot;shared&quot; DataContext that is used to fetch &quot;static&quot; read only lookup data. To avoid fetching the same data over and over again for each session, objects from the shared DataContext can be transferred to a session DataContext by calling <TT>DataContext.localObject()</TT>:</P>
<DIV class="code panel" style="border-width: 1px;"><DIV class="codeContent panelContent">
<PRE class="code-java">DataContext sessionContext = DataContext.getThreadDataContext();
HttpSession session; <SPAN class="code-comment">// assume <SPAN class="code-keyword">this</SPAN> exists
</SPAN>
<SPAN class="code-comment">// assume that ServletContext contains a list of UserType DataObjects
</SPAN><SPAN class="code-comment">// fetched via some global DataContext
</SPAN>List sharedUserTypes = (List) session.getServletContext().getAttribute(&quot;userTypes);
UserType sharedType = (UserType) sharedUserTypes.get(0);
UserType localType = (UserType) sessionContext.localObject(sharedType.getObjectId(), sharedType);
User user; <SPAN class="code-comment">// assume <SPAN class="code-keyword">this</SPAN> exists
</SPAN>
<SPAN class="code-comment">// now it is safe to use the UserType in relationships with other
</SPAN><SPAN class="code-comment">// session objects
</SPAN>user.setUserType(localType);
...</PRE>
</DIV></DIV>