Class DataContext

java.lang.Object
org.apache.cayenne.access.DataContext
All Implemented Interfaces:
ObjectContext

public class DataContext extends Object implements ObjectContext
The default implementation of ObjectContext.
  • Field Details

    • threadObjectContext

      @Deprecated(since="5.0", forRemoval=true) protected static final ThreadLocal<ObjectContext> threadObjectContext
      Deprecated, for removal: This API element is subject to removal in a future version.
      A holder of a ObjectContext bound to the current thread.
      Since:
      3.0
    • channel

      protected final DataChannel channel
    • objectStore

      protected final DataContextObjectStore objectStore
    • queryCache

      protected final QueryCache queryCache
    • entityResolver

      protected final EntityResolver entityResolver
    • validatingObjectsOnCommit

      protected final boolean validatingObjectsOnCommit
    • usingSharedSnapshotCache

      protected final boolean usingSharedSnapshotCache
    • userProperties

      protected volatile Map<String,Object> userProperties
      Stores user defined properties associated with this DataContext.
      Since:
      3.0
  • Constructor Details

    • DataContext

      protected DataContext(DataChannel channel, DataRowStore snapshotCache, Map<ObjectId, Persistent> objectMap, boolean syncWithSnapshotCache, boolean usingSharedSnapshotCache, boolean validatingObjectsOnCommit, QueryCache queryCache)
      Creates a DataContext and its ObjectStore as a single unit. Both objects reference each other, so the store is created here rather than passed in, keeping the reference immutable on both sides. Use builder(DataChannel) to create instances.
      Since:
      5.0
  • Method Details

    • getThreadObjectContext

      @Deprecated(since="5.0", forRemoval=true) public static ObjectContext getThreadObjectContext() throws IllegalStateException
      Deprecated, for removal: This API element is subject to removal in a future version.
      if you are using thread context, you can create your own ThreadLocal
      Returns the ObjectContext bound to the current thread.
      Returns:
      the ObjectContext associated with caller thread.
      Throws:
      IllegalStateException - if there is no ObjectContext bound to the current thread.
      Since:
      3.0
    • bindThreadObjectContext

      @Deprecated(since="5.0", forRemoval=true) public static void bindThreadObjectContext(ObjectContext context)
      Deprecated, for removal: This API element is subject to removal in a future version.
      if you are using thread context, you can create your own ThreadLocal
      Binds a ObjectContext to the current thread. ObjectContext can later be retrieved by users in the same thread by calling getThreadObjectContext(). Using null parameter will unbind currently bound ObjectContext.
      Since:
      3.0
    • builder

      public static DataContext.Builder builder(DataChannel channel)
      Starts building a DataContext attached to the given channel. All builder settings are optional.
      Since:
      5.0
    • getChannel

      public DataChannel getChannel()
      Description copied from interface: ObjectContext
      Returns a DataChannel that this context uses to access the persistent store.
      Specified by:
      getChannel in interface ObjectContext
    • getEntityResolver

      public EntityResolver getEntityResolver()
      Description copied from interface: ObjectContext
      Returns EntityResolver that stores all mapping information accessible by this ObjectContext.
      Specified by:
      getEntityResolver in interface ObjectContext
    • getParentDataDomain

      @Deprecated(since="5.0", forRemoval=true) public DataDomain getParentDataDomain()
      Deprecated, for removal: This API element is subject to removal in a future version.
      use DataChannel.getDataDomain() on the channel returned by getChannel()
      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 DataContextObjectStore getObjectStore()
      Description copied from interface: ObjectContext
      Returns the store of persistent objects registered with this context.
      Specified by:
      getObjectStore in interface ObjectContext
    • deleteObjects

      public <T extends Persistent> void deleteObjects(T... objects) throws DeleteDenyException
      Description copied from interface: ObjectContext
      Schedules deletion of one or more persistent objects.
      Specified by:
      deleteObjects in interface ObjectContext
      Throws:
      DeleteDenyException - if a DeleteRule.DENY delete rule is applicable for object deletion.
      Since:
      3.1
    • uncommittedObjects

      public Collection<Persistent> uncommittedObjects()
      Returns a collection of all uncommitted registered objects.
      Specified by:
      uncommittedObjects in interface ObjectContext
      Since:
      1.2
    • getQueryCache

      public QueryCache getQueryCache()
      Returns a cache for query results, set via DataContext.Builder.queryCache(QueryCache).
    • fireDataChannelCommitted

      protected void fireDataChannelCommitted(Object postedBy, GraphDiff changes)
      Since:
      1.2
    • fireDataChannelRolledback

      protected void fireDataChannelRolledback(Object postedBy, GraphDiff changes)
      Since:
      1.2
    • objectForPK

      public Persistent objectForPK(ObjectId id)
      Description copied from interface: ObjectContext
      Returns an object matching an ObjectId, or null if there's no such object. The id may be that of a superentity of the actual object entity.

      A resolved object registered in this context is returned without a query. Otherwise the object is looked up in the caches down the DataChannel stack, and then in the database.

      Specified by:
      objectForPK in interface ObjectContext
      Since:
      5.0
    • localObject

      public <T extends Persistent> T localObject(T objectFromAnotherContext)
      Description copied from interface: ObjectContext
      Returns a local copy of 'objectFromAnotherContext' object. "Local" means that the returned object is registered in this context. If the local object hasn't been previously cached in this context, a hollow object is created and returned to the caller. No DB query is performed to resolve an object.

      Note that passing an object with a non-existing id, may later result in FaultFailureException on attempt to read returned object properties.

      Specified by:
      localObject in interface ObjectContext
      Since:
      3.1
    • 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.

      Parameters:
      object - persistent object to create snapshot for
      Returns:
      current snapshot of the persistent object
      Since:
      1.1
    • prepareForAccess

      public void prepareForAccess(Persistent object, String property, boolean lazyFaulting)
      Description copied from interface: ObjectContext
      A callback method that child Persistent objects are expected to call before accessing property values. This callback allows ObjectContext to "inflate" unresolved objects on demand and also resolve properties that rely on lazy faulting.
      Specified by:
      prepareForAccess in interface ObjectContext
    • objectsFromDataRows

      public List objectsFromDataRows(ClassDescriptor descriptor, List<? extends DataRow> dataRows)
      Converts a list of DataRows to a List of Persistent registered with this DataContext.
      Since:
      3.0
    • objectFromDataRow

      public <T extends Persistent> T objectFromDataRow(Class<T> objectClass, DataRow dataRow)
      Creates a Persistent from DataRow.
      Since:
      3.1
      See Also:
    • objectFromDataRow

      public Persistent objectFromDataRow(String entityName, DataRow dataRow)
      Creates a Persistent from DataRow. This variety of the 'objectFromDataRow' method is normally used for generic classes.
      Since:
      3.1, 5.0 returns Persistent instead of the deprecated DataObject
      See Also:
    • newObject

      public Persistent newObject(String entityName)
      Description copied from interface: ObjectContext
      Creates a new persistent object of a given entity scheduled to be inserted to the database on next commit. The object class is determined from the mapped entity. In most cases ObjectContext.newObject(Class) should be used instead, but this method is helpful when generic persistent classes are used.
      Specified by:
      newObject in interface ObjectContext
    • registerNewObject

      public void registerNewObject(Persistent object)
      Registers a transient object with the context, recursively registering all transient persistent objects attached to this object via relationships.
      Specified by:
      registerNewObject in interface ObjectContext
      Parameters:
      object - new object that needs to be made persistent.
    • unregisterObjects

      public void unregisterObjects(Collection<? extends Persistent> objects)
      Unregisters a Collection of Persistent objects from the DataContext and the underlying ObjectStore. This operation also unsets DataContext for each object and changes its state to PersistenceState.TRANSIENT
      See Also:
    • invalidateObjects

      @SafeVarargs public final <T extends Persistent> void invalidateObjects(T... objects)
      Description copied from interface: ObjectContext
      Invalidates one or more persistent objects. Same as ObjectContext.invalidateObjects(Collection) only with a vararg argument list for easier invalidation of individual objects. If no arguments are passed to this method, it does nothing.
      Specified by:
      invalidateObjects in interface ObjectContext
      Since:
      3.1
    • invalidateObjects

      public void invalidateObjects(Collection<? extends Persistent> objects)
      Description copied from interface: ObjectContext
      Invalidates a Collection of persistent objects. This operation only applies to the objects already committed to the database and does nothing to the NEW objects. It would remove each object's snapshot from caches and change object's state to HOLLOW. On the next access to this object, the object will be refetched.
      Specified by:
      invalidateObjects in interface ObjectContext
    • propertyChanged

      public void propertyChanged(Persistent object, String property, Object oldValue, Object newValue)
      Description copied from interface: ObjectContext
      A callback method that child Persistent objects are expected to call from inside the setter after modifying a value of a persistent property, including "simple" and "arc" properties.
      Specified by:
      propertyChanged in interface ObjectContext
    • 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
      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
    • 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
      Since:
      1.2
      See Also:
    • 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
      Throws:
      CayenneRuntimeException
    • select

      public <T> List<T> select(Select<T> query)
      Description copied from interface: ObjectContext
      Executes a selecting query, returning a list of persistent objects or data rows.
      Specified by:
      select in interface ObjectContext
      Since:
      4.0
    • selectOne

      public <T> T selectOne(Select<T> query)
      Description copied from interface: ObjectContext
      Executes a selecting query, returning either NULL if query matched no objects, or a single object. If query matches more than one object, CayenneRuntimeException is thrown.
      Specified by:
      selectOne in interface ObjectContext
      Since:
      4.0
    • selectFirst

      public <T> T selectFirst(Select<T> query)
      Description copied from interface: ObjectContext
      Selects a single object using provided query. The query itself can match any number of objects, but will return only the first one. It returns null if no objects were matched.

      If it matched more than one object, the first object from the list is returned. This makes 'selectFirst' different from ObjectContext.selectOne(Select), which would throw in this situation. 'selectFirst' is useful e.g. when the query is ordered and we only want to see the first object (e.g. "most recent news article"), etc.

      Selecting the first object via "Select.selectFirst(ObjectContext)" is more comprehensible than selecting via "ObjectContext.selectFirst(Select)", because implementations of "Select" set fetch size limit to one.

      Specified by:
      selectFirst in interface ObjectContext
      Since:
      4.0
    • iterate

      public <T> void iterate(Select<T> query, ResultIteratorCallback<T> callback)
      Description copied from interface: ObjectContext
      Creates a ResultIterator based on the provided query and passes it to a callback for processing. The caller does not need to worry about closing the iterator. This method takes care of it.
      Specified by:
      iterate in interface ObjectContext
      Since:
      4.0
    • iterator

      public <T> ResultIterator<T> iterator(Select<T> query)
      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.

      Specified by:
      iterator in interface ObjectContext
    • execute

      public List<QueryResult> execute(Query query)
      Executes a query returning all of its result sets, update counts, iterators and OUT parameters in the order they were produced.
      Specified by:
      execute in interface ObjectContext
      Since:
      5.0
    • performNonSelectingQuery

      @Deprecated(since="5.0", forRemoval=true) public int[] performNonSelectingQuery(Query query)
      Deprecated, for removal: This API element is subject to removal in a future version.
      use execute(Query), or SQLExec.update(ObjectContext) / MappedExec.update(ObjectContext) for a query that produces a single update count
      Performs a single database query that does not select rows. Returns an array of update counts.
      Since:
      1.1
    • performNonSelectingQuery

      @Deprecated(since="5.0", forRemoval=true) public int[] performNonSelectingQuery(String queryName)
      Deprecated, for removal: This API element is subject to removal in a future version.
      use MappedExec.query(queryName).update(context)
      Performs a named mapped query that does not select rows. Returns an array of update counts.
      Since:
      1.1
    • performNonSelectingQuery

      @Deprecated(since="5.0", forRemoval=true) public int[] performNonSelectingQuery(String queryName, Map<String,?> parameters)
      Deprecated, for removal: This API element is subject to removal in a future version.
      use MappedExec.query(queryName).params(parameters).update(context)
      Performs a named mapped non-selecting query using a map of parameters. Returns an array of update counts.
      Since:
      1.1
    • performQuery

      @Deprecated(since="5.0", forRemoval=true) public List<?> performQuery(String queryName, boolean expireCachedLists)
      Deprecated, for removal: This API element is subject to removal in a future version.
      use MappedSelect.query(queryName).select(context), calling forceNoCache() on the query to expire cached lists
      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

      @Deprecated(since="5.0", forRemoval=true) public List<?> performQuery(String queryName, Map<String,?> parameters, boolean expireCachedLists)
      Deprecated, for removal: This API element is subject to removal in a future version.
      use MappedSelect.query(queryName).params(parameters).select(context), calling forceNoCache() on the query to expire cached lists
      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
    • fireDataChannelChanged

      protected void fireDataChannelChanged(Object postedBy, GraphDiff changes)
      Since:
      1.2
    • batchIterator

      public <T> ResultBatchIterator<T> batchIterator(Select<T> query, int size)
      Description copied from interface: ObjectContext
      Creates a ResultBatchIterator based on the provided query and batch size. It is usually backed by an open result set and is useful for processing of large data sets, preserving a constant memory footprint. The caller must wrap iteration in try/finally (or try-with-resources for Java 1.7 and higher) and close the ResultBatchIterator explicitly.
      Specified by:
      batchIterator in interface ObjectContext
    • isValidatingObjectsOnCommit

      public boolean isValidatingObjectsOnCommit()
      Returns whether this ObjectContext performs object validation before commit is executed. The flag is set via DataContext.Builder.validatingObjectsOnCommit(boolean).
      Since:
      1.1
    • getUserProperties

      protected Map<String,Object> getUserProperties()
      Returns a map of user-defined properties associated with this DataContext.
      Since:
      3.0
    • getUserProperty

      public Object getUserProperty(String key)
      Returns a user-defined property previously set via 'setUserProperty'. Note that it is a caller responsibility to synchronize access to properties.
      Specified by:
      getUserProperty in interface ObjectContext
      Since:
      3.0
    • setUserProperty

      public void setUserProperty(String key, Object value)
      Sets a user-defined property. Note that it is a caller responsibility to synchronize access to properties.
      Specified by:
      setUserProperty in interface ObjectContext
      Since:
      3.0
    • removeUserProperty

      public void removeUserProperty(String key)
      Removes a user-defined property.
      Specified by:
      removeUserProperty in interface ObjectContext
      Since:
      5.0
    • clearUserProperties

      public void clearUserProperties()
      Removes all user-defined properties.
      Specified by:
      clearUserProperties in interface ObjectContext
      Since:
      5.0