Cayenne User Documentation
Moving Objects Between Contexts

## Moving Objects Between Contexts

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 "shared" DataContext that is used to fetch "static" 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 `DataContext.localObject()`:

    DataContext sessionContext = DataContext.getThreadDataContext();

    HttpSession session; // assume this exists

    // assume that ServletContext contains a list of UserType DataObjects
    // fetched via some global DataContext
    List sharedUserTypes = (List) session.getServletContext().getAttribute("userTypes);
    UserType sharedType = (UserType) sharedUserTypes.get(0);

    UserType localType = (UserType) sessionContext.localObject(sharedType.getObjectId(), sharedType);
    User user; // assume this exists

    // now it is safe to use the UserType in relationships with other
    // session objects
    user.setUserType(localType);
    ...

.
Copyright ©2001-2010 Apache Software Foundation