Interface PersistenceContext


  • public interface PersistenceContext
    Represents the state of "stuff" Hibernate is tracking, including (not exhaustive):
    • entities
    • collections
    • snapshots
    • proxies

    Often referred to as the "first level cache".

    • Field Detail

      • NO_ROW

        static final java.lang.Object NO_ROW
        Marker object used to indicate (via reference checking) that no row was returned.
    • Method Detail

      • isStateless

        boolean isStateless()
      • getLoadContexts

        org.hibernate.engine.loading.internal.LoadContexts getLoadContexts()
        Retrieve this persistence context's managed load context.
        Returns:
        The load context
      • addUnownedCollection

        void addUnownedCollection​(CollectionKey key,
                                  PersistentCollection collection)
        Add a collection which has no owner loaded
        Parameters:
        key - The collection key under which to add the collection
        collection - The collection to add
      • useUnownedCollection

        PersistentCollection useUnownedCollection​(CollectionKey key)
        Take ownership of a previously unowned collection, if one. This method returns null if no such collection was previous added () or was previously removed.

        This should indicate the owner is being loaded and we are ready to "link" them.

        Parameters:
        key - The collection key for which to locate a collection collection
        Returns:
        The unowned collection, or null
      • getBatchFetchQueue

        BatchFetchQueue getBatchFetchQueue()
        Get the BatchFetchQueue, instantiating one if necessary.
        Returns:
        The batch fetch queue in effect for this persistence context
      • clear

        void clear()
        Clear the state of the persistence context
      • hasNonReadOnlyEntities

        boolean hasNonReadOnlyEntities()
        Returns:
        false if we know for certain that all the entities are read-only
      • setEntryStatus

        void setEntryStatus​(EntityEntry entry,
                            Status status)
        Set the status of an entry
        Parameters:
        entry - The entry for which to set the status
        status - The new status
      • afterTransactionCompletion

        void afterTransactionCompletion()
        Called after transactions end
      • getDatabaseSnapshot

        java.lang.Object[] getDatabaseSnapshot​(java.io.Serializable id,
                                               EntityPersister persister)
        Get the current state of the entity as known to the underlying database, or null if there is no corresponding row
        Parameters:
        id - The identifier of the entity for which to grab a snapshot
        persister - The persister of the entity.
        Returns:
        The entity's (non-cached) snapshot
        See Also:
        getCachedDatabaseSnapshot(org.hibernate.engine.spi.EntityKey)
      • getCachedDatabaseSnapshot

        java.lang.Object[] getCachedDatabaseSnapshot​(EntityKey key)
        Retrieve the cached database snapshot for the requested entity key.

        This differs from getDatabaseSnapshot(java.io.Serializable, org.hibernate.persister.entity.EntityPersister) is two important respects:

        1. no snapshot is obtained from the database if not already cached
        2. an entry of NO_ROW here is interpretet as an exception
        Parameters:
        key - The entity key for which to retrieve the cached snapshot
        Returns:
        The cached snapshot
        Throws:
        java.lang.IllegalStateException - if the cached snapshot was == NO_ROW.
      • getNaturalIdSnapshot

        java.lang.Object[] getNaturalIdSnapshot​(java.io.Serializable id,
                                                EntityPersister persister)
        Get the values of the natural id fields as known to the underlying database, or null if the entity has no natural id or there is no corresponding row.
        Parameters:
        id - The identifier of the entity for which to grab a snapshot
        persister - The persister of the entity.
        Returns:
        The current (non-cached) snapshot of the entity's natural id state.
      • addEntity

        void addEntity​(EntityKey key,
                       java.lang.Object entity)
        Add a canonical mapping from entity key to entity instance
        Parameters:
        key - The key under which to add an entity
        entity - The entity instance to add
      • getEntity

        java.lang.Object getEntity​(EntityKey key)
        Get the entity instance associated with the given key
        Parameters:
        key - The key under which to look for an entity
        Returns:
        The matching entity, or null
      • containsEntity

        boolean containsEntity​(EntityKey key)
        Is there an entity with the given key in the persistence context
        Parameters:
        key - The key under which to look for an entity
        Returns:
        true indicates an entity was found; otherwise false
      • removeEntity

        java.lang.Object removeEntity​(EntityKey key)
        Remove an entity. Also clears up all other state associated with the entity aside from the EntityEntry
        Parameters:
        key - The key whose matching entity should be removed
        Returns:
        The matching entity
      • addEntity

        void addEntity​(EntityUniqueKey euk,
                       java.lang.Object entity)
        Add an entity to the cache by unique key
        Parameters:
        euk - The unique (non-primary) key under which to add an entity
        entity - The entity instance
      • getEntity

        java.lang.Object getEntity​(EntityUniqueKey euk)
        Get an entity cached by unique key
        Parameters:
        euk - The unique (non-primary) key under which to look for an entity
        Returns:
        The located entity
      • getEntry

        EntityEntry getEntry​(java.lang.Object entity)
        Retrieve the EntityEntry representation of the given entity.
        Parameters:
        entity - The entity instance for which to locate the corresponding entry
        Returns:
        The entry
      • removeEntry

        EntityEntry removeEntry​(java.lang.Object entity)
        Remove an entity entry from the session cache
        Parameters:
        entity - The entity instance for which to remove the corresponding entry
        Returns:
        The matching entry
      • isEntryFor

        boolean isEntryFor​(java.lang.Object entity)
        Is there an EntityEntry registration for this entity instance?
        Parameters:
        entity - The entity instance for which to check for an entry
        Returns:
        true indicates a matching entry was found.
      • getCollectionEntry

        CollectionEntry getCollectionEntry​(PersistentCollection coll)
        Get the collection entry for a persistent collection
        Parameters:
        coll - The persistent collection instance for which to locate the collection entry
        Returns:
        The matching collection entry
      • addEntity

        EntityEntry addEntity​(java.lang.Object entity,
                              Status status,
                              java.lang.Object[] loadedState,
                              EntityKey entityKey,
                              java.lang.Object version,
                              LockMode lockMode,
                              boolean existsInDatabase,
                              EntityPersister persister,
                              boolean disableVersionIncrement)
        Adds an entity to the internal caches.
      • addEntry

        EntityEntry addEntry​(java.lang.Object entity,
                             Status status,
                             java.lang.Object[] loadedState,
                             java.lang.Object rowId,
                             java.io.Serializable id,
                             java.lang.Object version,
                             LockMode lockMode,
                             boolean existsInDatabase,
                             EntityPersister persister,
                             boolean disableVersionIncrement)
        Generates an appropriate EntityEntry instance and adds it to the event source's internal caches.
      • containsCollection

        boolean containsCollection​(PersistentCollection collection)
        Is the given collection associated with this persistence context?
      • containsProxy

        boolean containsProxy​(java.lang.Object proxy)
        Is the given proxy associated with this persistence context?
      • reassociateIfUninitializedProxy

        boolean reassociateIfUninitializedProxy​(java.lang.Object value)
                                         throws MappingException
        Takes the given object and, if it represents a proxy, reassociates it with this event source.
        Parameters:
        value - The possible proxy to be reassociated.
        Returns:
        Whether the passed value represented an actual proxy which got initialized.
        Throws:
        MappingException
      • reassociateProxy

        void reassociateProxy​(java.lang.Object value,
                              java.io.Serializable id)
                       throws MappingException
        If a deleted entity instance is re-saved, and it has a proxy, we need to reset the identifier of the proxy
        Throws:
        MappingException
      • unproxy

        java.lang.Object unproxy​(java.lang.Object maybeProxy)
                          throws HibernateException
        Get the entity instance underlying the given proxy, throwing an exception if the proxy is uninitialized. If the given object is not a proxy, simply return the argument.
        Throws:
        HibernateException
      • unproxyAndReassociate

        java.lang.Object unproxyAndReassociate​(java.lang.Object maybeProxy)
                                        throws HibernateException
        Possibly unproxy the given reference and reassociate it with the current session.
        Parameters:
        maybeProxy - The reference to be unproxied if it currently represents a proxy.
        Returns:
        The unproxied instance.
        Throws:
        HibernateException
      • checkUniqueness

        void checkUniqueness​(EntityKey key,
                             java.lang.Object object)
                      throws HibernateException
        Attempts to check whether the given key represents an entity already loaded within the current session.
        Parameters:
        object - The entity reference against which to perform the uniqueness check.
        Throws:
        HibernateException
      • narrowProxy

        java.lang.Object narrowProxy​(java.lang.Object proxy,
                                     EntityPersister persister,
                                     EntityKey key,
                                     java.lang.Object object)
                              throws HibernateException
        If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy and overwrite the registration of the old one. This breaks == and occurs only for "class" proxies rather than "interface" proxies. Also init the proxy to point to the given target implementation if necessary.
        Parameters:
        proxy - The proxy instance to be narrowed.
        persister - The persister for the proxied entity.
        key - The internal cache key for the proxied entity.
        object - (optional) the actual proxied entity instance.
        Returns:
        An appropriately narrowed instance.
        Throws:
        HibernateException
      • proxyFor

        java.lang.Object proxyFor​(EntityPersister persister,
                                  EntityKey key,
                                  java.lang.Object impl)
                           throws HibernateException
        Return the existing proxy associated with the given EntityKey, or the third argument (the entity associated with the key) if no proxy exists. Init the proxy to the target implementation, if necessary.
        Throws:
        HibernateException
      • proxyFor

        java.lang.Object proxyFor​(java.lang.Object impl)
                           throws HibernateException
        Return the existing proxy associated with the given EntityKey, or the argument (the entity associated with the key) if no proxy exists. (slower than the form above)
        Throws:
        HibernateException
      • getLoadedCollectionOwnerOrNull

        java.lang.Object getLoadedCollectionOwnerOrNull​(PersistentCollection collection)
        Get the entity that owned this persistent collection when it was loaded
        Parameters:
        collection - The persistent collection
        Returns:
        the owner if its entity ID is available from the collection's loaded key and the owner entity is in the persistence context; otherwise, returns null
      • getLoadedCollectionOwnerIdOrNull

        java.io.Serializable getLoadedCollectionOwnerIdOrNull​(PersistentCollection collection)
        Get the ID for the entity that owned this persistent collection when it was loaded
        Parameters:
        collection - The persistent collection
        Returns:
        the owner ID if available from the collection's loaded key; otherwise, returns null
      • addUninitializedCollection

        void addUninitializedCollection​(CollectionPersister persister,
                                        PersistentCollection collection,
                                        java.io.Serializable id)
        add a collection we just loaded up (still needs initializing)
      • addNonLazyCollection

        void addNonLazyCollection​(PersistentCollection collection)
        Register a collection for non-lazy loading at the end of the two-phase load
      • initializeNonLazyCollections

        void initializeNonLazyCollections()
                                   throws HibernateException
        Force initialization of all non-lazy collections encountered during the current two-phase load (actually, this is a no-op, unless this is the "outermost" load)
        Throws:
        HibernateException
      • getCollectionHolder

        PersistentCollection getCollectionHolder​(java.lang.Object array)
        Get the PersistentCollection object for an array
      • addCollectionHolder

        void addCollectionHolder​(PersistentCollection holder)
        Register a PersistentCollection object for an array. Associates a holder with an array - MUST be called after loading array, since the array instance is not created until endLoad().
      • removeCollectionHolder

        PersistentCollection removeCollectionHolder​(java.lang.Object array)
        Remove the mapping of collection to holder during eviction of the owning entity
      • getSnapshot

        java.io.Serializable getSnapshot​(PersistentCollection coll)
        Get the snapshot of the pre-flush collection state
      • getCollectionEntryOrNull

        CollectionEntry getCollectionEntryOrNull​(java.lang.Object collection)
        Get the collection entry for a collection passed to filter, which might be a collection wrapper, an array, or an unwrapped collection. Return null if there is no entry.
      • getProxy

        java.lang.Object getProxy​(EntityKey key)
        Get an existing proxy by key
      • addProxy

        void addProxy​(EntityKey key,
                      java.lang.Object proxy)
        Add a proxy to the session cache
      • removeProxy

        java.lang.Object removeProxy​(EntityKey key)
        Remove a proxy from the session cache.

        Additionally, ensure that any load optimization references such as batch or subselect loading get cleaned up as well.

        Parameters:
        key - The key of the entity proxy to be removed
        Returns:
        The proxy reference.
      • getNullifiableEntityKeys

        java.util.HashSet getNullifiableEntityKeys()
        Retrieve the set of EntityKeys representing nullifiable references
      • getEntitiesByKey

        java.util.Map getEntitiesByKey()
        Get the mapping from key value to entity instance
      • reentrantSafeEntityEntries

        java.util.Map.Entry<java.lang.Object,​EntityEntry>[] reentrantSafeEntityEntries()
        Provides access to the entity/EntityEntry combos associated with the persistence context in a manner that is safe from reentrant access. Specifically, it is safe from additions/removals while iterating.
        Returns:
      • getEntityEntries

        @Deprecated
        java.util.Map getEntityEntries()
        Deprecated.
        Due to the introduction of EntityEntryContext and bytecode enhancement; only valid really for sizing, see getNumberOfManagedEntities(). For iterating the entity/EntityEntry combos, see reentrantSafeEntityEntries()
        Get the mapping from entity instance to entity entry
      • getNumberOfManagedEntities

        int getNumberOfManagedEntities()
      • getCollectionEntries

        java.util.Map getCollectionEntries()
        Get the mapping from collection instance to collection entry
      • getCollectionsByKey

        java.util.Map getCollectionsByKey()
        Get the mapping from collection key to collection instance
      • getCascadeLevel

        int getCascadeLevel()
        How deep are we cascaded?
      • incrementCascadeLevel

        int incrementCascadeLevel()
        Called before cascading
      • decrementCascadeLevel

        int decrementCascadeLevel()
        Called after cascading
      • isFlushing

        boolean isFlushing()
        Is a flush cycle currently in process?
      • setFlushing

        void setFlushing​(boolean flushing)
        Called before and after the flushcycle
      • beforeLoad

        void beforeLoad()
        Call this before begining a two-phase load
      • afterLoad

        void afterLoad()
        Call this after finishing a two-phase load
      • isLoadFinished

        boolean isLoadFinished()
        Is in a two-phase load?
      • toString

        java.lang.String toString()
        Returns a string representation of the object.
        Overrides:
        toString in class java.lang.Object
        Returns:
        a string representation of the object.
      • getOwnerId

        java.io.Serializable getOwnerId​(java.lang.String entityName,
                                        java.lang.String propertyName,
                                        java.lang.Object childEntity,
                                        java.util.Map mergeMap)
        Search this persistence context for an associated entity instance which is considered the "owner" of the given childEntity, and return that owner's id value. This is performed in the scenario of a uni-directional, non-inverse one-to-many collection (which means that the collection elements do not maintain a direct reference to the owner).

        As such, the processing here is basically to loop over every entity currently associated with this persistence context and for those of the correct entity (sub) type to extract its collection role property value and see if the child is contained within that collection. If so, we have found the owner; if not, we go on.

        Also need to account for mergeMap which acts as a local copy cache managed for the duration of a merge operation. It represents a map of the detached entity instances pointing to the corresponding managed instance.

        Parameters:
        entityName - The entity name for the entity type which would own the child
        propertyName - The name of the property on the owning entity type which would name this child association.
        childEntity - The child entity instance for which to locate the owner instance id.
        mergeMap - A map of non-persistent instances from an on-going merge operation (possibly null).
        Returns:
        The id of the entityName instance which is said to own the child; null if an appropriate owner not located.
      • getIndexInOwner

        java.lang.Object getIndexInOwner​(java.lang.String entity,
                                         java.lang.String property,
                                         java.lang.Object childObject,
                                         java.util.Map mergeMap)
        Search the persistence context for an index of the child object, given a collection role
      • addNullProperty

        void addNullProperty​(EntityKey ownerKey,
                             java.lang.String propertyName)
        Record the fact that the association belonging to the keyed entity is null.
      • isPropertyNull

        boolean isPropertyNull​(EntityKey ownerKey,
                               java.lang.String propertyName)
        Is the association property belonging to the keyed entity null?
      • isDefaultReadOnly

        boolean isDefaultReadOnly()
        Will entities and proxies that are loaded into this persistence context be made read-only by default? To determine the read-only/modifiable setting for a particular entity or proxy:
        Returns:
        true, loaded entities/proxies will be made read-only by default; false, loaded entities/proxies will be made modifiable by default.
        See Also:
        isReadOnly(Object), Session.isReadOnly(Object), Session.isDefaultReadOnly()
      • setDefaultReadOnly

        void setDefaultReadOnly​(boolean readOnly)
        Change the default for entities and proxies loaded into this persistence context from modifiable to read-only mode, or from modifiable to read-only mode. Read-only entities are not dirty-checked and snapshots of persistent state are not maintained. Read-only entities can be modified, but changes are not persisted. When a proxy is initialized, the loaded entity will have the same read-only/modifiable setting as the uninitialized proxy has, regardless of the persistence context's current setting. To change the read-only/modifiable setting for a particular entity or proxy that is already in this session: + * @see PersistenceContext#setReadOnly(Object,boolean)
        Parameters:
        readOnly - true, the default for loaded entities/proxies is read-only; false, the default for loaded entities/proxies is modifiable
        See Also:
        To override this session's read-only/modifiable setting for entities and proxies loaded by a Query:, Query.setReadOnly(boolean), Session.setDefaultReadOnly(boolean)
      • isReadOnly

        boolean isReadOnly​(java.lang.Object entityOrProxy)
        Is the entity or proxy read-only?

        To determine the default read-only/modifiable setting used for entities and proxies that are loaded into the session use Session.isDefaultReadOnly()

        Parameters:
        entityOrProxy - an entity or proxy
        Returns:
        true if the object is read-only; otherwise false to indicate that the object is modifiable.
      • setReadOnly

        void setReadOnly​(java.lang.Object entityOrProxy,
                         boolean readOnly)
        Set an unmodified persistent object to read-only mode, or a read-only object to modifiable mode. Read-only entities are not dirty-checked and snapshots of persistent state are not maintained. Read-only entities can be modified, but changes are not persisted. When a proxy is initialized, the loaded entity will have the same read-only/modifiable setting as the uninitialized proxy has, regardless of the session's current setting. If the entity or proxy already has the specified read-only/modifiable setting, then this method does nothing.
        Parameters:
        entityOrProxy - an entity or proxy
        readOnly - if true, the entity or proxy is made read-only; otherwise, the entity or proxy is made modifiable.
        See Also:
        Session.setDefaultReadOnly(boolean), Session.setReadOnly(java.lang.Object, boolean), Query.setReadOnly(boolean)
      • replaceDelayedEntityIdentityInsertKeys

        void replaceDelayedEntityIdentityInsertKeys​(EntityKey oldKey,
                                                    java.io.Serializable generatedId)
      • addChildParent

        void addChildParent​(java.lang.Object child,
                            java.lang.Object parent)
        Add a child/parent relation to cache for cascading op
        Parameters:
        child - The child of the relationship
        parent - The parent of the relationship
      • removeChildParent

        void removeChildParent​(java.lang.Object child)
        Remove child/parent relation from cache
        Parameters:
        child - The child to be removed.
      • registerInsertedKey

        void registerInsertedKey​(EntityPersister persister,
                                 java.io.Serializable id)
        Register keys inserted during the current transaction
        Parameters:
        persister - The entity persister
        id - The id
      • wasInsertedDuringTransaction

        boolean wasInsertedDuringTransaction​(EntityPersister persister,
                                             java.io.Serializable id)
        Allows callers to check to see if the identified entity was inserted during the current transaction.
        Parameters:
        persister - The entity persister
        id - The id
        Returns:
        True if inserted during this transaction, false otherwise.
      • getNaturalIdHelper

        PersistenceContext.NaturalIdHelper getNaturalIdHelper()
        Access to the natural-id helper for this persistence context
        Returns:
        This persistence context's natural-id helper