org.apache.cayenne.access

## Class DataContext

- java.lang.Object
- - org.apache.cayenne.BaseContext
  - - org.apache.cayenne.access.DataContext

- All Implemented Interfaces:
    Serializable, DataChannel, ObjectContext

      public class DataContext
      extends BaseContext

  The most common implementation of `ObjectContext`. DataContext is an isolated container of an object graph, in a sense that any uncommitted changes to persistent objects that are registered with the context, are not visible to the users of other contexts.
  See Also:
    Serialized Form

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `protected org.apache.cayenne.access.DataContextMergeHandler` | `mergeHandler`
    `protected ObjectStore` | `objectStore`
    `protected boolean` | `usingSharedSnaphsotCache`

    - ### Fields inherited from class org.apache.cayenne.BaseContext

      `channel, entityResolver, graphAction, queryCache, threadObjectContext, userProperties, validatingObjectsOnCommit`

    - ### Fields inherited from interface org.apache.cayenne.DataChannel

      `FLUSH_CASCADE_SYNC, FLUSH_NOCASCADE_SYNC, GRAPH_CHANGED_SUBJECT, GRAPH_FLUSHED_SUBJECT, GRAPH_ROLLEDBACK_SUBJECT, ROLLBACK_CASCADE_SYNC`

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `DataContext()` Creates a new DataContext that is not attached to the Cayenne stack.
    `DataContext(DataChannel channel, ObjectStore objectStore)` Creates a new DataContext with parent DataChannel and ObjectStore.

  - ### Method Summary

    All Methods Instance Methods Concrete Methods Deprecated Methods
    Modifier and Type | Method and Description
    --- | ---
    `protected void` | `attachToChannel(DataChannel channel)` Attaches to a provided DataChannel.
    `void` | `commitChanges()` Synchronizes object graph with the database.
    `void` | `commitChangesToParent()` "Flushes" the changes to the parent `DataChannel`.
    `ObjectContext` | `createChildContext()` Deprecated. Since 3.1 replaced by `CayenneRuntime.getContext(DataChannel)`
    `DataRow` | `currentSnapshot(Persistent object)` Returns a DataRow reflecting current, possibly uncommitted, object state.
    `Collection<?>` | `deletedObjects()` Returns a list of objects that are registered with this DataContext and have a state PersistenceState.DELETED
    `protected void` | `fireDataChannelChanged(Object postedBy, GraphDiff changes)`
    `DataContextDelegate` | `getDelegate()` Returns a delegate currently associated with this DataContext.
    `GraphManager` | `getGraphManager()` Returns this context's ObjectStore.
    `ObjectStore` | `getObjectStore()` Returns ObjectStore associated with this DataContext.
    `DataDomain` | `getParentDataDomain()` Returns a DataDomain used by this DataContext.
    `boolean` | `hasChanges()` Returns `true` if there are any modified, deleted or new objects registered with this DataContext, `false` otherwise.
    `boolean` | `isUsingSharedSnapshotCache()` Returns `true` if the ObjectStore uses shared cache of a parent DataDomain.
    `Collection<?>` | `modifiedObjects()` Returns a list of objects that are registered with this DataContext and have a state PersistenceState.MODIFIED
    `<T> T` | `newObject(Class<T> persistentClass)` Creates and registers a new persistent object.
    `Persistent` | `newObject(String entityName)` Instantiates a new object and registers it with this context.
    `Collection<?>` | `newObjects()` Returns a list of objects that are registered with this DataContext and have a state PersistenceState.NEW
    `<T extends DataObject> T` | `objectFromDataRow(Class<T> objectClass, DataRow dataRow)` Creates a DataObject from DataRow.
    `<T extends DataObject> T` | `objectFromDataRow(Class<T> objectClass, DataRow dataRow, boolean refresh)` Deprecated. Use objectFromDataRow(Class objectClass, DataRow dataRow) instead.
    `DataObject` | `objectFromDataRow(String entityName, DataRow dataRow)` Creates a DataObject from DataRow.
    `DataObject` | `objectFromDataRow(String entityName, DataRow dataRow, boolean refresh)` Deprecated. Use objectFromDataRow(String entityName, DataRow dataRow) instead.
    `List` | `objectsFromDataRows(ClassDescriptor descriptor, List<? extends DataRow> dataRows)` Converts a list of DataRows to a List of DataObject registered with this DataContext.
    `protected GraphDiff` | `onContextFlush(ObjectContext originatingContext, GraphDiff changes, boolean cascade)`
    `QueryResponse` | `onQuery(ObjectContext context, Query query)` An implementation of a `DataChannel` method that is used by child contexts to execute queries.
    `QueryResponse` | `performGenericQuery(Query query)` Executes a query returning a generic response.
    `ResultIterator` | `performIteratedQuery(Query query)` Performs a single database select query returning result as a ResultIterator.
    `int[]` | `performNonSelectingQuery(Query query)` Performs a single database query that does not select rows.
    `int[]` | `performNonSelectingQuery(String queryName)` Performs a named mapped query that does not select rows.
    `int[]` | `performNonSelectingQuery(String queryName, Map<String,?> parameters)` Performs a named mapped non-selecting query using a map of parameters.
    `List` | `performQuery(Query query)` Performs a single selecting query.
    `List<?>` | `performQuery(String queryName, boolean expireCachedLists)` Returns a list of objects or DataRows for a named query stored in one of the DataMaps.
    `List<?>` | `performQuery(String queryName, Map parameters, boolean expireCachedLists)` Returns a list of objects or DataRows for a named query stored in one of the DataMaps.
    `void` | `registerNewObject(Object object)` Registers a transient object with the context, recursively registering all transient persistent objects attached to this object via relationships.
    `void` | `rollbackChanges()` Reverts any changes that have occurred to objects registered with DataContext; also performs cascading rollback of all parent DataContexts.
    `void` | `rollbackChangesLocally()` If the parent channel is a DataContext, reverts local changes to make this context look like the parent, if the parent channel is a DataDomain, reverts all changes.
    `void` | `setDelegate(DataContextDelegate delegate)` Sets a DataContextDelegate for this context.
    `void` | `setUsingSharedSnapshotCache(boolean flag)`
    `Collection<?>` | `uncommittedObjects()` Returns a collection of all uncommitted registered objects.
    `void` | `unregisterObjects(Collection dataObjects)` Unregisters a Collection of DataObjects from the DataContext and the underlying ObjectStore.

    - ### Methods inherited from class org.apache.cayenne.BaseContext

      `attachToRuntime, attachToRuntimeIfNeeded, bindThreadObjectContext, deleteObject, deleteObjects, deleteObjects, fireDataChannelCommitted, fireDataChannelRolledback, getChannel, getEntityResolver, getEventManager, getQueryCache, getThreadObjectContext, getUserProperties, getUserProperty, injectInitialValue, invalidateObjects, invalidateObjects, isValidatingObjectsOnCommit, localObject, localObject, onSync, prepareForAccess, propertyChanged, setChannel, setEntityResolver, setQueryCache, setUserProperty, setValidatingObjectsOnCommit`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Field Detail

    - #### usingSharedSnaphsotCache

          protected boolean usingSharedSnaphsotCache

    - #### objectStore

          protected ObjectStore objectStore

    - #### mergeHandler

          protected transient org.apache.cayenne.access.DataContextMergeHandler mergeHandler

  - ### Constructor Detail

    - #### DataContext

          public DataContext()

      Creates a new DataContext that is not attached to the Cayenne stack.

    - #### DataContext

          public DataContext(DataChannel channel,
                             ObjectStore objectStore)

      Creates a new DataContext with parent DataChannel and ObjectStore.
      Since:
        1.2

  - ### Method Detail

    - #### createChildContext

          @Deprecated
          public ObjectContext createChildContext()

      Deprecated. Since 3.1 replaced by `CayenneRuntime.getContext(DataChannel)`
      Creates and returns a new child ObjectContext.
      Since:
        3.0

    - #### attachToChannel

          protected void attachToChannel(DataChannel channel)

      Description copied from class: `BaseContext`
      Attaches to a provided DataChannel.
      Overrides:
        `attachToChannel` in class `BaseContext`
      Since:
        3.1

    - #### getParentDataDomain

          public DataDomain getParentDataDomain()

      Returns a DataDomain used by this DataContext. DataDomain is looked up in the DataChannel hierarchy. If a channel is not a DataDomain or a DataContext, null is returned.
      Returns:
        DataDomain that is a direct or indirect parent of this DataContext in the DataChannel hierarchy.
      Since:
        1.1

    - #### setDelegate

          public void setDelegate(DataContextDelegate delegate)

      Sets a DataContextDelegate for this context. Delegate is notified of certain events in the DataContext lifecycle and can customize DataContext behavior.
      Since:
        1.1

    - #### getDelegate

          public DataContextDelegate getDelegate()

      Returns a delegate currently associated with this DataContext.
      Since:
        1.1

    - #### getObjectStore

          public ObjectStore getObjectStore()

      Returns ObjectStore associated with this DataContext.

    - #### hasChanges

          public boolean hasChanges()

      Returns `true` if there are any modified, deleted or new objects registered with this DataContext, `false` otherwise.

    - #### newObjects

          public Collection<?> newObjects()

      Returns a list of objects that are registered with this DataContext and have a state PersistenceState.NEW
      Specified by:
        `newObjects` in interface `ObjectContext`
      Specified by:
        `newObjects` in class `BaseContext`

    - #### deletedObjects

          public Collection<?> deletedObjects()

      Returns a list of objects that are registered with this DataContext and have a state PersistenceState.DELETED
      Specified by:
        `deletedObjects` in interface `ObjectContext`
      Specified by:
        `deletedObjects` in class `BaseContext`

    - #### modifiedObjects

          public Collection<?> modifiedObjects()

      Returns a list of objects that are registered with this DataContext and have a state PersistenceState.MODIFIED
      Specified by:
        `modifiedObjects` in interface `ObjectContext`
      Specified by:
        `modifiedObjects` in class `BaseContext`

    - #### uncommittedObjects

          public Collection<?> uncommittedObjects()

      Returns a collection of all uncommitted registered objects.
      Specified by:
        `uncommittedObjects` in interface `ObjectContext`
      Specified by:
        `uncommittedObjects` in class `BaseContext`
      Since:
        1.2

    - #### currentSnapshot

          public DataRow currentSnapshot(Persistent object)

      Returns a DataRow reflecting current, possibly uncommitted, object state.

      Warning: This method will return a partial snapshot if an object or one of its related objects that propagate their keys to this object have temporary ids. DO NOT USE this method if you expect a DataRow to represent a complete object state.

      Since:
        1.1

    - #### objectsFromDataRows

          public List objectsFromDataRows(ClassDescriptor descriptor,
                                          List<? extends DataRow> dataRows)

      Converts a list of DataRows to a List of DataObject registered with this DataContext.
      Since:
        3.0

    - #### objectFromDataRow

          @Deprecated
          public <T extends DataObject> T objectFromDataRow(Class<T> objectClass,
                                                                         DataRow dataRow,
                                                                         boolean refresh)

      Deprecated. Use objectFromDataRow(Class objectClass, DataRow dataRow) instead.
      Creates a DataObject from DataRow.
      See Also:
        `DataRow`

    - #### objectFromDataRow

          public <T extends DataObject> T objectFromDataRow(Class<T> objectClass,
                                                            DataRow dataRow)

      Creates a DataObject from DataRow.
      Since:
        3.1
      See Also:
        `DataRow`

    - #### objectFromDataRow

          @Deprecated
          public DataObject objectFromDataRow(String entityName,
                                                           DataRow dataRow,
                                                           boolean refresh)

      Deprecated. Use objectFromDataRow(String entityName, DataRow dataRow) instead.
      Creates a DataObject from DataRow. This variety of the 'objectFromDataRow' method is normally used for generic classes.
      Since:
        3.0
      See Also:
        `DataRow`

    - #### objectFromDataRow

          public DataObject objectFromDataRow(String entityName,
                                              DataRow dataRow)

      Creates a DataObject from DataRow. This variety of the 'objectFromDataRow' method is normally used for generic classes.
      Since:
        3.1
      See Also:
        `DataRow`

    - #### newObject

          public <T> T newObject(Class<T> persistentClass)

      Creates and registers a new persistent object.
      Specified by:
        `newObject` in interface `ObjectContext`
      Specified by:
        `newObject` in class `BaseContext`
      Since:
        1.2

    - #### newObject

          public Persistent newObject(String entityName)

      Instantiates a new object and registers it with this context. Object class is determined from the mapped entity. Object class must have a default constructor.

      Note: in most cases `newObject(Class)` method should be used, however this method is helpful when generic persistent classes are used.
      Since:
        3.0

    - #### registerNewObject

          public void registerNewObject(Object object)

      Registers a transient object with the context, recursively registering all transient persistent objects attached to this object via relationships.

      Note that since 3.0 this method takes Object as an argument instead of a `DataObject`.
      Specified by:
        `registerNewObject` in interface `ObjectContext`
      Specified by:
        `registerNewObject` in class `BaseContext`
      Parameters:
        `object` - new object that needs to be made persistent.

    - #### unregisterObjects

          public void unregisterObjects(Collection dataObjects)

      Unregisters a Collection of DataObjects from the DataContext and the underlying ObjectStore. This operation also unsets DataContext and ObjectId for each object and changes its state to TRANSIENT.
      See Also:
        `BaseContext.invalidateObjects(Collection)`

    - #### rollbackChangesLocally

          public void rollbackChangesLocally()

      If the parent channel is a DataContext, reverts local changes to make this context look like the parent, if the parent channel is a DataDomain, reverts all changes.
      Specified by:
        `rollbackChangesLocally` in interface `ObjectContext`
      Specified by:
        `rollbackChangesLocally` in class `BaseContext`
      Since:
        1.2

    - #### rollbackChanges

          public void rollbackChanges()

      Reverts any changes that have occurred to objects registered with DataContext; also performs cascading rollback of all parent DataContexts.
      Specified by:
        `rollbackChanges` in interface `ObjectContext`
      Specified by:
        `rollbackChanges` in class `BaseContext`

    - #### commitChangesToParent

          public void commitChangesToParent()

      "Flushes" the changes to the parent `DataChannel`. If the parent channel is a DataContext, it updates its objects with this context's changes, without a database update. If it is a DataDomain (the most common case), the changes are written to the database. To cause cascading commit all the way to the database, one must use `commitChanges()`.
      Specified by:
        `commitChangesToParent` in interface `ObjectContext`
      Specified by:
        `commitChangesToParent` in class `BaseContext`
      Since:
        1.2
      See Also:
        `commitChanges()`

    - #### commitChanges

          public void commitChanges()
                             throws CayenneRuntimeException

      Synchronizes object graph with the database. Executes needed insert, update and delete queries (generated internally).
      Specified by:
        `commitChanges` in interface `ObjectContext`
      Specified by:
        `commitChanges` in class `BaseContext`
      Throws:
        `CayenneRuntimeException`

    - #### onContextFlush

          protected GraphDiff onContextFlush(ObjectContext originatingContext,
                                             GraphDiff changes,
                                             boolean cascade)

      Specified by:
        `onContextFlush` in class `BaseContext`

    - #### performIteratedQuery

          public ResultIterator performIteratedQuery(Query query)
                                              throws CayenneException

      Performs a single database select query returning result as a ResultIterator. It is caller's responsibility to explicitly close the ResultIterator. A failure to do so will result in a database connection not being released. Another side effect of an open ResultIterator is that an internal Cayenne transaction that originated in this method stays open until the iterator is closed. So users should normally close the iterator within the same thread that opened it.
      Throws:
        `CayenneException`

    - #### performGenericQuery

          public QueryResponse performGenericQuery(Query query)

      Executes a query returning a generic response.
      Specified by:
        `performGenericQuery` in interface `ObjectContext`
      Specified by:
        `performGenericQuery` in class `BaseContext`
      Since:
        1.2

    - #### performQuery

          public List performQuery(Query query)

      Performs a single selecting query. Various query setting control the behavior of this method and the results returned:
      - Query caching policy defines whether the results are retrieved from cache or fetched from the database. Note that queries that use caching must have a name that is used as a caching key.
      - Query refreshing policy controls whether to refresh existing data objects and ignore any cached values.
      - Query data rows policy defines whether the result should be returned as DataObjects or DataRows.

      Since 1.2 takes any Query parameter, not just GenericSelectQuery

      Specified by:
        `performQuery` in interface `ObjectContext`
      Specified by:
        `performQuery` in class `BaseContext`
      Returns:
        A list of DataObjects or a DataRows, depending on the value returned by `QueryMetadata.isFetchingDataRows()`.

    - #### onQuery

          public QueryResponse onQuery(ObjectContext context,
                                       Query query)

      An implementation of a `DataChannel` method that is used by child contexts to execute queries. Not intended for direct use.
      Parameters:
        `context` - an ObjectContext that originated the query, used to register result objects.
      Returns:
        a generic response object that encapsulates result of the execution.
      Since:
        1.2

    - #### performNonSelectingQuery

          public int[] performNonSelectingQuery(Query query)

      Performs a single database query that does not select rows. Returns an array of update counts.
      Since:
        1.1

    - #### performNonSelectingQuery

          public int[] performNonSelectingQuery(String queryName)

      Performs a named mapped query that does not select rows. Returns an array of update counts.
      Since:
        1.1

    - #### performNonSelectingQuery

          public int[] performNonSelectingQuery(String queryName,
                                                Map<String,?> parameters)

      Performs a named mapped non-selecting query using a map of parameters. Returns an array of update counts.
      Since:
        1.1

    - #### performQuery

          public List<?> performQuery(String queryName,
                                      boolean expireCachedLists)

      Returns a list of objects or DataRows for a named query stored in one of the DataMaps. Internally Cayenne uses a caching policy defined in the named query. If refresh flag is true, a refresh is forced no matter what the caching policy is.
      Parameters:
        `queryName` - a name of a GenericSelectQuery defined in one of the DataMaps. If no such query is defined, this method will throw a CayenneRuntimeException.
        `expireCachedLists` - A flag that determines whether refresh of cached lists is required in case a query uses caching.
      Since:
        1.1

    - #### performQuery

          public List<?> performQuery(String queryName,
                                      Map parameters,
                                      boolean expireCachedLists)

      Returns a list of objects or DataRows for a named query stored in one of the DataMaps. Internally Cayenne uses a caching policy defined in the named query. If refresh flag is true, a refresh is forced no matter what the caching policy is.
      Parameters:
        `queryName` - a name of a GenericSelectQuery defined in one of the DataMaps. If no such query is defined, this method will throw a CayenneRuntimeException.
        `parameters` - A map of parameters to use with stored query.
        `expireCachedLists` - A flag that determines whether refresh of cached lists is required in case a query uses caching.
      Since:
        1.1

    - #### isUsingSharedSnapshotCache

          public boolean isUsingSharedSnapshotCache()

      Returns `true` if the ObjectStore uses shared cache of a parent DataDomain.
      Since:
        1.1

    - #### setUsingSharedSnapshotCache

          public void setUsingSharedSnapshotCache(boolean flag)

      Since:
        3.1

    - #### getGraphManager

          public GraphManager getGraphManager()

      Returns this context's ObjectStore.
      Specified by:
        `getGraphManager` in interface `ObjectContext`
      Specified by:
        `getGraphManager` in class `BaseContext`
      Since:
        1.2

    - #### fireDataChannelChanged

          protected void fireDataChannelChanged(Object postedBy,
                                                GraphDiff changes)

      Overrides:
        `fireDataChannelChanged` in class `BaseContext`

Copyright © 2001–2018 Apache Cayenne. All rights reserved.