Class SessionImpl
- All Implemented Interfaces:
EntityManager
,Serializable
,AutoCloseable
,LobCreationContext
,SessionImplementor
,SharedSessionContractImplementor
,EventSource
,LoadAccessContext
,QueryProducer
,QueryProducerImplementor
,JdbcSessionOwner
,TransactionCoordinatorBuilder.Options
,Session
,SharedSessionContract
,JavaType.CoercionContext
,WrapperOptions
Session
API.
Exposes two interfaces:
Session
to the application, andSessionImplementor
andEventSource
(both SPI interfaces) to other subsystems.
This class is not thread-safe.
- See Also:
- Implementation Note:
- The
SessionImpl
does not directly perform operations against the database or second-level cache. Instead, it is anEventSource
, raising events which are processed by various implementations of the listener interfaces defined byorg.hibernate.event.spi
. These listeners typically placeEntityAction
instances on theActionQueue
associated with the session, and such actions are executed asynchronously when the session is flushed. The motivation behind this architecture is two-fold: first, it enables customization by sophisticated extensions to Hibernate ORM, and, second, it enables the transactional write-behind semantics of a stateful session. The stateful session holds its state in an instance ofStatefulPersistenceContext
, which we may view as the first-level cache associated with the session.
-
Nested Class Summary
Nested classes/interfaces inherited from interface org.hibernate.engine.jdbc.LobCreationContext
LobCreationContext.Callback<T>
-
Field Summary
Fields inherited from class org.hibernate.internal.AbstractSharedSessionContract
closed, waitingForAutoClose
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid
addEventListeners
(SessionEventListener... listeners) Add one or more listeners to the Sessionprotected void
addSharedSessionTransactionObserver
(TransactionCoordinator transactionCoordinator) void
afterOperation
(boolean success) Check if there is a Hibernate or JTA transaction in progress and, if there is not, flush if necessary, making sure that the connection has been committed (if it is not in autocommit mode), and finally run the after completion processing.void
Called after each operation on aScrollableResults
, providing an opportunity for a stateless session to clear its temporary persistence context.void
An after-begin callback from the coordinator to its owner.void
afterTransactionCompletion
(boolean successful, boolean delayed) An after-completion callback to the owner.protected void
applyLockOptionsHint
(SelectionQuery<?> query) protected void
applyQuerySettingsAndHints
(Query<?> query) protected void
applyQuerySettingsAndHints
(SelectionQuery<?> query) Cast this session toEventSource
if possible.boolean
autoFlushIfRequired
(Set<String> querySpaces) detect in-memory changes, determine if the changes are to tables named in the query and, if so, complete execution the flushboolean
autoFlushIfRequired
(Set<String> querySpaces, boolean skipPreFlush) void
void
A before-completion callback to the owner.bestGuessEntityName
(Object object) Obtain the best estimate of the entity name of the given entity instance, which is not involved in an association, by also considering information held in the proxy, and whether the object is already associated with this session.bestGuessEntityName
(Object object, EntityEntry entry) Obtain the best estimate of the entity name of the given entity instance, which is not involved in an association, by also considering information held in the proxy, and whether the object is already associated with this session.<T> IdentifierLoadAccessImpl<T>
Create anIdentifierLoadAccess
instance to retrieve an instance of the given entity type by its primary key.<T> IdentifierLoadAccessImpl<T>
Create anIdentifierLoadAccess
instance to retrieve an instance of the named entity type by its primary key.<T> MultiIdentifierLoadAccess<T>
byMultipleIds
(Class<T> entityClass) Create aMultiIdentifierLoadAccess
instance to retrieve multiple instances of the given entity type by their primary key values, using batching.<T> MultiIdentifierLoadAccess<T>
byMultipleIds
(String entityName) Create aMultiIdentifierLoadAccess
instance to retrieve multiple instances of the named entity type by their primary key values, using batching.<T> NaturalIdMultiLoadAccess<T>
byMultipleNaturalId
(Class<T> entityClass) Create aMultiIdentifierLoadAccess
instance to retrieve multiple instances of the given entity type by their by natural id values, using batching.<T> NaturalIdMultiLoadAccess<T>
byMultipleNaturalId
(String entityName) Create aMultiIdentifierLoadAccess
instance to retrieve multiple instances of the named entity type by their by natural id values, using batching.<T> NaturalIdLoadAccess<T>
byNaturalId
(Class<T> entityClass) Create aNaturalIdLoadAccess
instance to retrieve an instance of the given entity type by its natural id, which may be a composite natural id.<T> NaturalIdLoadAccess<T>
byNaturalId
(String entityName) Create aNaturalIdLoadAccess
instance to retrieve an instance of the named entity type by its natural id, which may be a composite natural id.<T> SimpleNaturalIdLoadAccess<T>
bySimpleNaturalId
(Class<T> entityClass) Create aSimpleNaturalIdLoadAccess
instance to retrieve an instance of the given entity type by its natural id, which must be a simple (non-composite) value.<T> SimpleNaturalIdLoadAccess<T>
bySimpleNaturalId
(String entityName) Create aSimpleNaturalIdLoadAccess
instance to retrieve an instance of the named entity type by its natural id, which must be a simple (non-composite) value.void
Cancel the execution of the current query.protected void
protected void
void
Callback to check whether the session is "active"protected void
protected void
clear all the internal collections, just to help the garbage collector, does not clear anything that is needed during the afterTransactionCompletion() phasevoid
clear()
Completely clear the session.void
close()
End the session by releasing the JDBC connection and cleaning up.void
boolean
boolean
Determine if the given entity is associated with this session.protected ActionQueue
Obtain aProcedureCall
based on a named templateprotected PersistenceContext
<T> QueryImplementor<T>
createQuery
(CriteriaSelect<T> selectQuery) createStoredProcedureCall
(String procedureName) Create aProcedureCall
to a stored procedure.createStoredProcedureCall
(String procedureName, Class<?>... resultClasses) Create aProcedureCall
to a stored procedure with the given result set entity mappings.createStoredProcedureCall
(String procedureName, String... resultSetMappings) Create aProcedureCall
to a stored procedure with the given result set entity mappings.createStoredProcedureQuery
(String procedureName) Create aProcedureCall
to a stored procedure.createStoredProcedureQuery
(String procedureName, Class... resultClasses) Create aProcedureCall
to a stored procedure with the given result set entity mappings.createStoredProcedureQuery
(String procedureName, String... resultSetMappings) Create aProcedureCall
to a stored procedure with the given result set entity mappings.void
void
delete
(String entityName, Object object, boolean isCascadeDeleteEnabled, DeleteContext transientEntities) Cascade delete an entity instancevoid
Remove this instance from the session cache.protected CacheMode
determineAppropriateLocalCacheMode
(Map<String, Object> localProperties) void
disableFetchProfile
(String name) Disable thefetch profile
with the given name in this session.void
enableFetchProfile
(String name) Enable thefetch profile
with the given name in this session.void
remove any hard references to the entity that are held by the infrastructure (references held by application or other persistent instances are okay)<T> T
find
(EntityGraph<T> entityGraph, Object primaryKey, FindOption... options) <T> T
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.<T> T
find
(Class<T> entityClass, Object primaryKey, FindOption... options) <T> T
find
(Class<T> entityClass, Object primaryKey, LockModeType lockModeType) <T> T
find
(Class<T> entityClass, Object primaryKey, LockModeType lockModeType, Map<String, Object> properties) <T> T
<T> T
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.<T> T
find
(Class<T> entityType, Object id, LockOptions lockOptions) Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.<E> List<E>
findMultiple
(Class<E> entityType, List<Object> ids, FindOption... options) Return the persistent instances of the given entity class with the given identifiers as a list.void
flush()
Flush this session.void
void
forceFlush
(EntityEntry entityEntry) Initiate a flush to force deletion of a re-persisted entity.void
forceFlush
(EntityKey key) Initiate a flush to force deletion of a re-persisted entity.<T> T
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.<T> T
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.<T> T
get
(Class<T> entityClass, Object id, LockOptions lockOptions) Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance.Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.get
(String entityName, Object id, LockOptions lockOptions) Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.Get theActionQueue
associated with this session.The JPA-definedCacheRetrieveMode
.The JPA-definedCacheStoreMode
.getContextEntityIdentifier
(Object object) Get the id value for an object that is actually associated with the session.getCurrentLockMode
(Object object) Determine the currentLockMode
of the given managed instance associated with this session.getEntityName
(Object object) Return the entity name for a persistent entity.getEntityPersister
(String entityName, Object object) Get theEntityPersister
for the given entity instance.Get the entity instance associated with the givenEntityKey
, calling theInterceptor
if necessary.int
Get the maximum batch size for batch fetching associations by id in this session.getIdentifier
(Object object) Return the identifier value of the given entity associated with this session.Get theLoadQueryInfluencers
associated with this session.getLockMode
(Object entity) Get the persistence context for this session.Similar toSharedSessionContractImplementor.getPersistenceContext()
, with two differences: this version performs better as it allows for inlining and probably better prediction, and it skips some checks of the current state of the session.<T> T
getReference
(Class<T> entityClass, Object id) Return a reference to the persistent instance with the given class and identifier, making the assumption that the instance is still persistent in the database.getReference
(String entityName, Object id) Return a reference to the persistent instance of the given named entity with the given identifier, making the assumption that the instance is still persistent in the database.<T> T
getReference
(T object) Return a reference to the persistent instance with the same identity as the given instance, which might be detached, making the assumption that the instance is still persistent in the database.Returns this object, fulfilling the contract ofWrapperOptions
.Get the statistics for this session.guessEntityName
(Object object) Obtain an estimate of the entity name of the given entity instance, which is not involved in an association, using only theEntityNameResolver
.immediateLoad
(String entityName, Object id) Load the data for the object with the specified id into a newly created object.void
initializeCollection
(PersistentCollection<?> collection, boolean writing) Initialize the given collection (if not already initialized).instantiate
(String entityName, Object id) Instantiate the entity class, initializing with the given identifier.instantiate
(EntityPersister persister, Object id) give the interceptor an opportunity to override the default instantiationinternalLoad
(String entityName, Object id, boolean eager, boolean nullable) Obtain an entity instance with the given id, without checking if it was deleted or scheduled for deletion.protected static LoadEventListener.LoadType
internalLoadType
(boolean eager, boolean nullable) boolean
Is auto-close at transaction completion enabled?boolean
Are entities and proxies loaded by this session read-only by default?boolean
isDirty()
Does this session contain any changes which must be synchronized with the database? In other words, would any DML operations be executed if we flushed this session?boolean
Determines if this session implementsEventSource
.boolean
isFetchProfileEnabled
(String name) Is thefetch profile
with the given name enabled in this session?boolean
isOpen()
Check if the session is still open.boolean
isReadOnly
(Object entityOrProxy) Is the specified entity or proxy read-only?boolean
Determine if subselect fetching is enabled in this session.void
Read the persistent state associated with the given identifier into the given transient instance.load
(LoadEventListener.LoadType loadType, Object id, String entityName, LockOptions lockOptions, Boolean readOnly) Efficiently fire aLoadEvent
with the given type and return the resulting entity instance or proxy.loadFromSecondLevelCache
(EntityPersister persister, EntityKey entityKey, Object instanceToLoad, LockMode lockMode) Attempts to load the entity from the second-level cache.void
lock
(Object entity, LockModeType lockModeType) void
lock
(Object entity, LockModeType lockModeType, LockOption... options) void
void
Obtain the specified lock level on the given managed instance associated with this session.void
lock
(Object object, LockOptions lockOptions) Obtain a lock on the given managed instance associated with this session, using the given lock options.void
lock
(String entityName, Object object, LockOptions lockOptions) Cascade the lock operation to the given child entity.void
merge
(String entityName, Object object, MergeContext copiedAlready) Cascade merge an entity instance<T> T
Copy the state of the given object onto the persistent object with the same identifier.<T> T
merge
(T object) Copy the state of the given object onto the persistent object with the same identifier.void
Make a transient instance persistent and mark it for later insertion in the database.void
Make a transient instance persistent and mark it for later insertion in the database.void
persist
(String entityName, Object object, PersistContext copiedAlready) Cascade persist an entity instancevoid
persistOnFlush
(String entityName, Object object, PersistContext copiedAlready) Cascade persist an entity instance during the flush processvoid
Callback to pulse the transaction coovoid
Reread the state of the given managed instance associated with this session from the underlying database.void
refresh
(Object entity, LockModeType lockModeType) void
void
refresh
(Object entity, RefreshOption... options) void
void
Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode
.void
refresh
(Object object, LockOptions lockOptions) Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode
.void
refresh
(String entityName, Object object, RefreshContext refreshedAlready) Cascade refresh an entity instancevoid
Mark a persistence instance associated with this session for removal from the underlying database.void
removeOrphanBeforeUpdates
(String entityName, Object child) A specialized type of deletion for orphan removal that must occur prior to queued inserts and updates.protected void
removeSharedSessionTransactionObserver
(TransactionCoordinator transactionCoordinator) void
replicate
(Object obj, ReplicationMode replicationMode) Persist the state of the given detached instance, reusing the current identifier value.void
replicate
(String entityName, Object obj, ReplicationMode replicationMode) Persist the state of the given detached instance, reusing the current identifier value.Obtain aSession
builder with the ability to copy certain information from this session.void
setAutoClear
(boolean enabled) Enable or disable automatic cache clearing from after transaction completion.void
setCacheRetrieveMode
(CacheRetrieveMode cacheRetrieveMode) Enable or disable reads from the second-level cache.void
setCacheStoreMode
(CacheStoreMode cacheStoreMode) Enable or disable writes to the second-level cache.void
setDefaultReadOnly
(boolean defaultReadOnly) Change the default for entities and proxies loaded into this session from modifiable to read-only mode, or from modifiable to read-only mode.void
setFetchBatchSize
(int batchSize) Set the maximum batch size for batch fetching associations by id in this session.void
setFlushMode
(FlushModeType flushModeType) Set the current JPA flush mode for this session.void
setProperty
(String propertyName, Object value) void
setReadOnly
(Object entity, boolean readOnly) Set an unmodified persistent object to read-only mode, or a read-only object to modifiable mode.void
setSubselectFetchingEnabled
(boolean enabled) Enable or disable subselect fetching in this session.boolean
Should this session be automatically closed after the current transaction completes?protected boolean
shouldCloseJdbcCoordinatorOnClose
(boolean isTransactionCoordinatorShared) void
Callback indicating recognition of entering into a transactional context whether that is explicitly via the HibernateTransaction
API or via registration of Hibernate's JTA Synchronization impl with a JTA TransactiontoString()
<T> T
Methods inherited from class org.hibernate.internal.AbstractSharedSessionContract
accessTransaction, addResultType, beginTransaction, buildNamedQuery, buildNamedQuery, checkMutationQuery, checkOpen, checkResultType, checkSelectionQuery, checkTransactionNeededForUpdateOperation, checkTransactionSynchStatus, createCriteriaQuery, createEntityGraph, createEntityGraph, createEntityGraph, createMutationQuery, createMutationQuery, createMutationQuery, createMutationQuery, createMutationQuery, createNamedMutationQuery, createNamedQuery, createNamedQuery, createNamedSelectionQuery, createNamedSelectionQuery, createNativeMutationQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQueryImplementor, createNativeQueryImplementor, createQuery, createQuery, createQuery, createQuery, createQuery, createQuery, createSelectionQuery, createSelectionQuery, createSelectionQuery, createSqmQueryImplementor, createSqmQueryImplementor, disableFilter, doReturningWork, doWork, enableFilter, execute, generateEntityKey, getCacheMode, getCacheTransactionSynchronization, getConfiguredJdbcBatchSize, getCriteriaBuilder, getCurrentTransaction, getDialect, getEnabledFilter, getEntityGraph, getEntityGraphs, getEntityNameResolver, getEventListenerManager, getEventMonitor, getExceptionConverter, getFactory, getFlushMode, getHibernateFlushMode, getInterceptor, getJdbcBatchSize, getJdbcConnectionAccess, getJdbcCoordinator, getJdbcServices, getJdbcSessionContext, getJdbcTimeZone, getJsonFormatMapper, getLobCreator, getNamedNativeQuery, getNamedNativeQuery, getNamedProcedureCall, getNamedQuery, getNativeJdbcParametersIgnored, getPreferredSqlTypeCodeForBoolean, getResultSetMappingMemento, getSessionFactory, getSessionIdentifier, getSessionToken, getTenantIdentifier, getTenantIdentifierValue, getTransaction, getTransactionCoordinator, getTypeConfiguration, getXmlFormatMapper, interpretHql, isClosed, isConnected, isCriteriaCopyTreeEnabled, isJoinedToTransaction, isOpenOrWaitingForAutoClose, isTransactionInProgress, joinTransaction, markForRollbackOnly, prepareForAutoClose, prepareForQueryExecution, setCacheMode, setClosed, setCriteriaCopyTreeEnabled, setHibernateFlushMode, setJdbcBatchSize, setNativeJdbcParametersIgnored, setUpMultitenancy, shouldAutoJoinTransaction, useStreamForLobBinding
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface jakarta.persistence.EntityManager
createNativeQuery, createNativeQuery, createNativeQuery, getCriteriaBuilder, getTransaction, isJoinedToTransaction, joinTransaction
Methods inherited from interface org.hibernate.resource.jdbc.spi.JdbcSessionOwner
getEventManager, getEventMonitor, getJdbcBatchSize, getJdbcConnectionAccess, getJdbcSessionContext, getSqlExceptionHelper, getTransactionCoordinator
Methods inherited from interface org.hibernate.engine.jdbc.LobCreationContext
execute, fromContext
Methods inherited from interface org.hibernate.query.QueryProducer
createMutationQuery, createMutationQuery, createNamedSelectionQuery, createNamedSelectionQuery, createSelectionQuery, createSelectionQuery, createSelectionQuery
Methods inherited from interface org.hibernate.query.spi.QueryProducerImplementor
createMutationQuery, createMutationQuery, createMutationQuery, createNamedMutationQuery, createNamedQuery, createNamedQuery, createNativeMutationQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createQuery, createQuery, createQuery, createQuery, createQuery, createQuery, getCacheMode, getNamedNativeQuery, getNamedNativeQuery, getNamedQuery
Methods inherited from interface org.hibernate.Session
createNamedQuery, createNamedQuery, createQuery, createQuery, createQuery, createQuery, createQuery, createQuery, getCacheMode, getEntityGraphs, getFlushMode, getHibernateFlushMode, setCacheMode, setHibernateFlushMode
Methods inherited from interface org.hibernate.engine.spi.SessionImplementor
asSessionImplementor, callWithConnection, createEntityGraph, createEntityGraph, getEntityGraph, getSessionFactory, isSessionImplementor, runWithConnection
Methods inherited from interface org.hibernate.SharedSessionContract
beginTransaction, createEntityGraph, disableFilter, doReturningWork, doWork, enableFilter, getCriteriaBuilder, getEnabledFilter, getJdbcBatchSize, getNamedProcedureCall, getTenantIdentifier, getTenantIdentifierValue, getTransaction, isConnected, isJoinedToTransaction, joinTransaction, setJdbcBatchSize
Methods inherited from interface org.hibernate.engine.spi.SharedSessionContractImplementor
accessTransaction, asStatelessSession, checkOpen, checkOpen, checkTransactionNeededForUpdateOperation, generateEntityKey, getCacheTransactionSynchronization, getConfiguredJdbcBatchSize, getDialect, getEventListenerManager, getExceptionConverter, getFactory, getFlushMode, getHibernateFlushMode, getInterceptor, getJdbcCoordinator, getJdbcServices, getNativeJdbcParametersIgnored, getSessionFactory, getSessionIdentifier, getSessionToken, getTypeConfiguration, isClosed, isCriteriaCopyTreeEnabled, isOpenOrWaitingForAutoClose, isStatelessSession, isTransactionInProgress, markForRollbackOnly, prepareForQueryExecution, setCriteriaCopyTreeEnabled, setHibernateFlushMode, setNativeJdbcParametersIgnored
Methods inherited from interface org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder.Options
shouldAutoJoinTransaction
Methods inherited from interface org.hibernate.type.descriptor.WrapperOptions
getJdbcTimeZone, getJsonFormatMapper, getLobCreator, getPreferredSqlTypeCodeForBoolean, getXmlFormatMapper, useStreamForLobBinding
-
Constructor Details
-
SessionImpl
-
-
Method Details
-
createPersistenceContext
-
createActionQueue
-
applyQuerySettingsAndHints
- Overrides:
applyQuerySettingsAndHints
in classAbstractSharedSessionContract
-
applyLockOptionsHint
-
applyQuerySettingsAndHints
- Overrides:
applyQuerySettingsAndHints
in classAbstractSharedSessionContract
-
sessionWithOptions
Description copied from interface:Session
Obtain aSession
builder with the ability to copy certain information from this session.- Specified by:
sessionWithOptions
in interfaceSession
- Returns:
- the session builder
-
clear
public void clear()Description copied from interface:Session
Completely clear the session. Evict all loaded instances and cancel all pending saves, updates and deletions. Do not close open iterators or instances ofScrollableResults
.- Specified by:
clear
in interfaceEntityManager
- Specified by:
clear
in interfaceSession
-
close
public void close()Description copied from interface:SharedSessionContract
End the session by releasing the JDBC connection and cleaning up.- Specified by:
close
in interfaceAutoCloseable
- Specified by:
close
in interfaceEntityManager
- Specified by:
close
in interfaceSharedSessionContract
- Overrides:
close
in classAbstractSharedSessionContract
-
closeWithoutOpenChecks
public void closeWithoutOpenChecks() -
shouldCloseJdbcCoordinatorOnClose
protected boolean shouldCloseJdbcCoordinatorOnClose(boolean isTransactionCoordinatorShared) - Overrides:
shouldCloseJdbcCoordinatorOnClose
in classAbstractSharedSessionContract
-
isAutoCloseSessionEnabled
public boolean isAutoCloseSessionEnabled()Description copied from interface:SharedSessionContractImplementor
Is auto-close at transaction completion enabled?- Specified by:
isAutoCloseSessionEnabled
in interfaceSharedSessionContractImplementor
- See Also:
-
isOpen
public boolean isOpen()Description copied from interface:SharedSessionContract
Check if the session is still open.- Specified by:
isOpen
in interfaceEntityManager
- Specified by:
isOpen
in interfaceSharedSessionContract
- Overrides:
isOpen
in classAbstractSharedSessionContract
- Returns:
true
if it is open
-
checkSessionFactoryOpen
protected void checkSessionFactoryOpen() -
shouldAutoClose
public boolean shouldAutoClose()Description copied from interface:SharedSessionContractImplementor
Should this session be automatically closed after the current transaction completes?- Specified by:
shouldAutoClose
in interfaceSharedSessionContractImplementor
-
setAutoClear
public void setAutoClear(boolean enabled) Description copied from interface:SharedSessionContractImplementor
Enable or disable automatic cache clearing from after transaction completion.- Specified by:
setAutoClear
in interfaceSharedSessionContractImplementor
-
afterOperation
public void afterOperation(boolean success) Description copied from interface:SharedSessionContractImplementor
Check if there is a Hibernate or JTA transaction in progress and, if there is not, flush if necessary, making sure that the connection has been committed (if it is not in autocommit mode), and finally run the after completion processing.- Specified by:
afterOperation
in interfaceSharedSessionContractImplementor
- Parameters:
success
-true
if the operation a success
-
addEventListeners
Description copied from interface:Session
Add one or more listeners to the Session- Specified by:
addEventListeners
in interfaceSession
- Parameters:
listeners
- the listener(s) to add
-
cleanupOnClose
protected void cleanupOnClose()clear all the internal collections, just to help the garbage collector, does not clear anything that is needed during the afterTransactionCompletion() phase- Overrides:
cleanupOnClose
in classAbstractSharedSessionContract
-
getCurrentLockMode
Description copied from interface:Session
Determine the currentLockMode
of the given managed instance associated with this session.- Specified by:
getCurrentLockMode
in interfaceSession
- Parameters:
object
- a persistent instance associated with this session- Returns:
- the current lock mode
-
getEntityUsingInterceptor
Description copied from interface:SharedSessionContractImplementor
Get the entity instance associated with the givenEntityKey
, calling theInterceptor
if necessary.- Specified by:
getEntityUsingInterceptor
in interfaceSharedSessionContractImplementor
-
checkNoUnresolvedActionsBeforeOperation
protected void checkNoUnresolvedActionsBeforeOperation() -
checkNoUnresolvedActionsAfterOperation
protected void checkNoUnresolvedActionsAfterOperation() -
delayedAfterCompletion
public void delayedAfterCompletion()- Specified by:
delayedAfterCompletion
in interfaceLoadAccessContext
- Overrides:
delayedAfterCompletion
in classAbstractSharedSessionContract
-
pulseTransactionCoordinator
public void pulseTransactionCoordinator()Description copied from interface:LoadAccessContext
Callback to pulse the transaction coo- Specified by:
pulseTransactionCoordinator
in interfaceLoadAccessContext
- Overrides:
pulseTransactionCoordinator
in classAbstractSharedSessionContract
-
checkOpenOrWaitingForAutoClose
public void checkOpenOrWaitingForAutoClose()Description copied from interface:LoadAccessContext
Callback to check whether the session is "active"- Specified by:
checkOpenOrWaitingForAutoClose
in interfaceLoadAccessContext
-
lock
Description copied from interface:Session
Obtain a lock on the given managed instance associated with this session, using the given lock options.This operation cascades to associated instances if the association is mapped with
CascadeType.LOCK
. -
lock
Description copied from interface:SessionImplementor
Cascade the lock operation to the given child entity.- Specified by:
lock
in interfaceSessionImplementor
-
lock
Description copied from interface:Session
Obtain the specified lock level on the given managed instance associated with this session. This operation may be used to:- perform a version check on an entity read from the second-level cache
by requesting
LockMode.READ
, - schedule a version check at transaction commit by requesting
LockMode.OPTIMISTIC
, - schedule a version increment at transaction commit by requesting
LockMode.OPTIMISTIC_FORCE_INCREMENT
- upgrade to a pessimistic lock with
LockMode.PESSIMISTIC_READ
orLockMode.PESSIMISTIC_WRITE
, or - immediately increment the version of the given instance by requesting
LockMode.PESSIMISTIC_FORCE_INCREMENT
.
If the requested lock mode is already held on the given entity, this operation has no effect.
This operation cascades to associated instances if the association is mapped with
CascadeType.LOCK
.The modes
LockMode.WRITE
andLockMode.UPGRADE_SKIPLOCKED
are not legal arguments tolock()
. - perform a version check on an entity read from the second-level cache
by requesting
-
persist
Description copied from interface:Session
Make a transient instance persistent and mark it for later insertion in the database. This operation cascades to associated instances if the association is mapped withCascadeType.PERSIST
.For entities with a
generated id
,persist()
ultimately results in generation of an identifier for the given instance. But this may happen asynchronously, when the session is flushed, depending on the identifier generation strategy. -
persist
Description copied from interface:Session
Make a transient instance persistent and mark it for later insertion in the database. This operation cascades to associated instances if the association is mapped withCascadeType.PERSIST
.For an entity with a generated id,
persist()
ultimately results in generation of an identifier for the given instance. But this may happen asynchronously, when the session is flushed, depending on the identifier generation strategy.- Specified by:
persist
in interfaceEntityManager
- Specified by:
persist
in interfaceSession
- Parameters:
object
- a transient instance to be made persistent
-
persist
Description copied from interface:EventSource
Cascade persist an entity instance- Specified by:
persist
in interfaceEventSource
-
persistOnFlush
Description copied from interface:EventSource
Cascade persist an entity instance during the flush process- Specified by:
persistOnFlush
in interfaceEventSource
-
merge
Description copied from interface:Session
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped withCascadeType.MERGE
. -
merge
public <T> T merge(T object) Description copied from interface:Session
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped withCascadeType.MERGE
.- Specified by:
merge
in interfaceEntityManager
- Specified by:
merge
in interfaceSession
- Parameters:
object
- a detached instance with state to be copied- Returns:
- an updated persistent instance
-
merge
Description copied from interface:EventSource
Cascade merge an entity instance- Specified by:
merge
in interfaceEventSource
-
delete
public void delete(String entityName, Object object, boolean isCascadeDeleteEnabled, DeleteContext transientEntities) Description copied from interface:EventSource
Cascade delete an entity instance- Specified by:
delete
in interfaceEventSource
-
removeOrphanBeforeUpdates
Description copied from interface:EventSource
A specialized type of deletion for orphan removal that must occur prior to queued inserts and updates.- Specified by:
removeOrphanBeforeUpdates
in interfaceEventSource
-
load
Description copied from interface:Session
Read the persistent state associated with the given identifier into the given transient instance. -
findMultiple
Description copied from interface:Session
Return the persistent instances of the given entity class with the given identifiers as a list. The position of an instance in the returned list matches the position of its identifier in the given list of identifiers, and the returned list contains a null value if there is no persistent instance matching a given identifier. If an instance is already associated with the session, that instance is returned. This method never returns an uninitialized instance.Every object returned by
findMultiple()
is either an unproxied instance of the given entity class, or a fully-fetched proxy object.This method accepts
BatchSize
as an option, allowing control over the number of records retrieved in a single database request. The performance impact of setting a batch size depends on whether a SQL array may be used to pass the list of identifiers to the database:- for databases which support standard SQL arrays, a smaller batch size might be extremely inefficient compared to a very large batch size or no batching at all, but
- on the other hand, for databases with no SQL array type, a large batch size results in long SQL statements with many JDBC parameters.
For more advanced cases, use
Session.byMultipleIds(Class)
, which returns an instance ofMultiIdentifierLoadAccess
.- Specified by:
findMultiple
in interfaceSession
- Parameters:
entityType
- the entity typeids
- the list of identifiersoptions
- options, if any- Returns:
- an ordered list of persistent instances, with null elements representing missing entities, whose positions in the list match the positions of their ids in the given list of identifiers
- See Also:
-
get
Description copied from interface:Session
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.The object returned by
get()
orfind()
is either an unproxied instance of the given entity class, or a fully-fetched proxy object.This operation requests
LockMode.NONE
, that is, no lock, allowing the object to be retrieved from the cache without the cost of database access. However, if it is necessary to read the state from the database, the object will be returned with the lock modeLockMode.READ
.To bypass the second-level cache, and ensure that the state is read from the database, either:
- call
Session.get(Class, Object, LockMode)
with the explicit lock modeLockMode.READ
, or - set the cache mode to
CacheMode.IGNORE
before calling this method.
- call
-
get
Description copied from interface:Session
Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance. -
immediateLoad
Load the data for the object with the specified id into a newly created object. This is only called when lazily initializing a proxy. Do NOT return a proxy.- Specified by:
immediateLoad
in interfaceSharedSessionContractImplementor
-
internalLoad
Description copied from interface:SharedSessionContractImplementor
Obtain an entity instance with the given id, without checking if it was deleted or scheduled for deletion.- When
nullable = false
, this method may create a new proxy or return an existing proxy; if it does not exist, an exception is thrown. - When
nullable = true
, the method does not create new proxies, though it might return an existing proxy; if it does not exist, anull
value is returned.
When
eager = true
, the object is eagerly fetched from the database.- Specified by:
internalLoad
in interfaceSharedSessionContractImplementor
- When
-
internalLoadType
-
loadFromSecondLevelCache
public Object loadFromSecondLevelCache(EntityPersister persister, EntityKey entityKey, Object instanceToLoad, LockMode lockMode) Description copied from interface:EventSource
Attempts to load the entity from the second-level cache.- Specified by:
loadFromSecondLevelCache
in interfaceEventSource
- Parameters:
persister
- The persister for the entity being requested for loadentityKey
- The entity keyinstanceToLoad
- The instance that is being initialized, or nulllockMode
- The lock mode- Returns:
- The entity from the second-level cache, or null.
-
get
Description copied from interface:Session
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance. Obtain the specified lock mode if the instance exists.Convenient form of
Session.get(Class, Object, LockOptions)
. -
get
Description copied from interface:Session
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance. Obtain the specified lock mode if the instance exists. -
get
Description copied from interface:Session
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance. Obtain the specified lock mode if the instance exists.Convenient form of
Session.get(String, Object, LockOptions)
-
get
Description copied from interface:Session
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance. Obtain the specified lock mode if the instance exists. -
byId
Description copied from interface:Session
Create anIdentifierLoadAccess
instance to retrieve an instance of the named entity type by its primary key.- Specified by:
byId
in interfaceSession
- Parameters:
entityName
- the entity name of the entity type to be retrieved- Returns:
- an instance of
IdentifierLoadAccess
for executing the lookup
-
byId
Description copied from interface:Session
Create anIdentifierLoadAccess
instance to retrieve an instance of the given entity type by its primary key.- Specified by:
byId
in interfaceSession
- Parameters:
entityClass
- the entity type to be retrieved- Returns:
- an instance of
IdentifierLoadAccess
for executing the lookup
-
byMultipleIds
Description copied from interface:Session
Create aMultiIdentifierLoadAccess
instance to retrieve multiple instances of the given entity type by their primary key values, using batching.- Specified by:
byMultipleIds
in interfaceSession
- Parameters:
entityClass
- the entity type to be retrieved- Returns:
- an instance of
MultiIdentifierLoadAccess
for executing the lookup - See Also:
-
byMultipleIds
Description copied from interface:Session
Create aMultiIdentifierLoadAccess
instance to retrieve multiple instances of the named entity type by their primary key values, using batching.- Specified by:
byMultipleIds
in interfaceSession
- Parameters:
entityName
- the entity name of the entity type to be retrieved- Returns:
- an instance of
MultiIdentifierLoadAccess
for executing the lookup
-
byNaturalId
Description copied from interface:Session
Create aNaturalIdLoadAccess
instance to retrieve an instance of the named entity type by its natural id, which may be a composite natural id. The entity must have at least one attribute annotatedNaturalId
.- Specified by:
byNaturalId
in interfaceSession
- Parameters:
entityName
- the entity name of the entity type to be retrieved- Returns:
- an instance of
NaturalIdLoadAccess
for executing the lookup
-
byNaturalId
Description copied from interface:Session
Create aNaturalIdLoadAccess
instance to retrieve an instance of the given entity type by its natural id, which may be a composite natural id. The entity must have at least one attribute annotatedNaturalId
.- Specified by:
byNaturalId
in interfaceSession
- Parameters:
entityClass
- the entity type to be retrieved- Returns:
- an instance of
NaturalIdLoadAccess
for executing the lookup
-
bySimpleNaturalId
Description copied from interface:Session
Create aSimpleNaturalIdLoadAccess
instance to retrieve an instance of the named entity type by its natural id, which must be a simple (non-composite) value. The entity must have exactly one attribute annotatedNaturalId
.- Specified by:
bySimpleNaturalId
in interfaceSession
- Parameters:
entityName
- the entity name of the entity type to be retrieved- Returns:
- an instance of
SimpleNaturalIdLoadAccess
for executing the lookup
-
bySimpleNaturalId
Description copied from interface:Session
Create aSimpleNaturalIdLoadAccess
instance to retrieve an instance of the given entity type by its natural id, which must be a simple (non-composite) value. The entity must have exactly one attribute annotatedNaturalId
.- Specified by:
bySimpleNaturalId
in interfaceSession
- Parameters:
entityClass
- the entity type to be retrieved- Returns:
- an instance of
SimpleNaturalIdLoadAccess
for executing the lookup
-
byMultipleNaturalId
Description copied from interface:Session
Create aMultiIdentifierLoadAccess
instance to retrieve multiple instances of the given entity type by their by natural id values, using batching.- Specified by:
byMultipleNaturalId
in interfaceSession
- Parameters:
entityClass
- the entity type to be retrieved- Returns:
- an instance of
NaturalIdMultiLoadAccess
for executing the lookup
-
byMultipleNaturalId
Description copied from interface:Session
Create aMultiIdentifierLoadAccess
instance to retrieve multiple instances of the named entity type by their by natural id values, using batching.- Specified by:
byMultipleNaturalId
in interfaceSession
- Parameters:
entityName
- the entity name of the entity type to be retrieved- Returns:
- an instance of
NaturalIdMultiLoadAccess
for executing the lookup
-
load
public Object load(LoadEventListener.LoadType loadType, Object id, String entityName, LockOptions lockOptions, Boolean readOnly) Description copied from interface:LoadAccessContext
Efficiently fire aLoadEvent
with the given type and return the resulting entity instance or proxy.- Specified by:
load
in interfaceLoadAccessContext
-
refresh
Description copied from interface:Session
Reread the state of the given managed instance associated with this session from the underlying database. This may be useful:- when a database trigger alters the object state upon insert or update,
- after executing any HQL update or delete statement,
- after executing a native SQL statement, or
- after inserting a
Blob
orClob
.
This operation cascades to associated instances if the association is mapped with
CascadeType.REFRESH
.This operation requests
LockMode.READ
. To obtain a stronger lock, callSession.refresh(Object, LockMode)
.- Specified by:
refresh
in interfaceEntityManager
- Specified by:
refresh
in interfaceSession
- Parameters:
object
- a persistent instance associated with this session
-
refresh
Description copied from interface:Session
Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode
.Convenient form of
Session.refresh(Object, LockOptions)
-
refresh
Description copied from interface:Session
Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode
. -
refresh
Description copied from interface:EventSource
Cascade refresh an entity instance- Specified by:
refresh
in interfaceEventSource
-
replicate
Description copied from interface:Session
Persist the state of the given detached instance, reusing the current identifier value. This operation cascades to associated instances if the association is mapped withCascadeType.REPLICATE
. -
replicate
Description copied from interface:Session
Persist the state of the given detached instance, reusing the current identifier value. This operation cascades to associated instances if the association is mapped withCascadeType.REPLICATE
. -
evict
remove any hard references to the entity that are held by the infrastructure (references held by application or other persistent instances are okay) -
autoFlushIfRequired
Description copied from interface:SharedSessionContractImplementor
detect in-memory changes, determine if the changes are to tables named in the query and, if so, complete execution the flush- Specified by:
autoFlushIfRequired
in interfaceSharedSessionContractImplementor
- Parameters:
querySpaces
- the tables named in the query.- Returns:
- true if flush is required, false otherwise.
-
autoFlushIfRequired
- Specified by:
autoFlushIfRequired
in interfaceSharedSessionContractImplementor
-
autoPreFlush
public void autoPreFlush()- Specified by:
autoPreFlush
in interfaceSharedSessionContractImplementor
-
isDirty
public boolean isDirty()Description copied from interface:Session
Does this session contain any changes which must be synchronized with the database? In other words, would any DML operations be executed if we flushed this session? -
flush
public void flush()Description copied from interface:SharedSessionContractImplementor
Flush this session.- Specified by:
flush
in interfaceEntityManager
- Specified by:
flush
in interfaceSession
- Specified by:
flush
in interfaceSharedSessionContractImplementor
-
setFlushMode
Description copied from interface:Session
Set the current JPA flush mode for this session.Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. The current flush mode determines when the session is automatically flushed.
- Specified by:
setFlushMode
in interfaceEntityManager
- Specified by:
setFlushMode
in interfaceSession
- Parameters:
flushModeType
- the newFlushModeType
- See Also:
-
forceFlush
Description copied from interface:SessionImplementor
Initiate a flush to force deletion of a re-persisted entity.- Specified by:
forceFlush
in interfaceEventSource
- Specified by:
forceFlush
in interfaceSessionImplementor
-
forceFlush
Description copied from interface:SessionImplementor
Initiate a flush to force deletion of a re-persisted entity.- Specified by:
forceFlush
in interfaceEventSource
- Specified by:
forceFlush
in interfaceSessionImplementor
-
instantiate
Description copied from interface:SharedSessionContractImplementor
Instantiate the entity class, initializing with the given identifier.- Specified by:
instantiate
in interfaceSharedSessionContractImplementor
-
instantiate
give the interceptor an opportunity to override the default instantiation- Specified by:
instantiate
in interfaceEventSource
- Specified by:
instantiate
in interfaceSessionImplementor
- Specified by:
instantiate
in interfaceSharedSessionContractImplementor
-
getEntityPersister
Description copied from interface:SharedSessionContractImplementor
Get theEntityPersister
for the given entity instance.- Specified by:
getEntityPersister
in interfaceSharedSessionContractImplementor
- Parameters:
entityName
- optional entity nameobject
- the entity instance
-
getIdentifier
Description copied from interface:Session
Return the identifier value of the given entity associated with this session. An exception is thrown if the given entity instance is transient or detached in relation to this session.- Specified by:
getIdentifier
in interfaceSession
- Parameters:
object
- a persistent instance associated with this session- Returns:
- the identifier
-
getContextEntityIdentifier
Get the id value for an object that is actually associated with the session. This is a bit stricter thanForeignKeys.getEntityIdentifierIfNotUnsaved(java.lang.String, java.lang.Object, org.hibernate.engine.spi.SharedSessionContractImplementor)
.- Specified by:
getContextEntityIdentifier
in interfaceSharedSessionContractImplementor
-
contains
- Specified by:
contains
in interfaceEntityManager
-
contains
Description copied from interface:Session
Determine if the given entity is associated with this session. -
createStoredProcedureCall
Description copied from interface:SharedSessionContract
Create aProcedureCall
to a stored procedure.- Specified by:
createStoredProcedureCall
in interfaceSharedSessionContract
- Overrides:
createStoredProcedureCall
in classAbstractSharedSessionContract
- Parameters:
procedureName
- The name of the procedure.- Returns:
- The representation of the procedure call.
-
createStoredProcedureCall
Description copied from interface:SharedSessionContract
Create aProcedureCall
to a stored procedure with the given result set entity mappings.- Specified by:
createStoredProcedureCall
in interfaceSharedSessionContract
- Overrides:
createStoredProcedureCall
in classAbstractSharedSessionContract
- Parameters:
procedureName
- The name of the procedure.resultSetMappings
- The explicit result set mapping(s) to use for mapping the results- Returns:
- The representation of the procedure call.
-
createStoredProcedureCall
Description copied from interface:SharedSessionContract
Create aProcedureCall
to a stored procedure with the given result set entity mappings. Each given class is considered a "root return".- Specified by:
createStoredProcedureCall
in interfaceSharedSessionContract
- Overrides:
createStoredProcedureCall
in classAbstractSharedSessionContract
- Parameters:
procedureName
- The name of the procedure.resultClasses
- The entity(s) to map the result on to.- Returns:
- The representation of the procedure call.
-
createQuery
- Specified by:
createQuery
in interfaceEntityManager
- Specified by:
createQuery
in interfaceSessionImplementor
-
initializeCollection
Description copied from interface:SharedSessionContractImplementor
Initialize the given collection (if not already initialized).- Specified by:
initializeCollection
in interfaceSharedSessionContractImplementor
-
bestGuessEntityName
Description copied from interface:SharedSessionContractImplementor
Obtain the best estimate of the entity name of the given entity instance, which is not involved in an association, by also considering information held in the proxy, and whether the object is already associated with this session.- Specified by:
bestGuessEntityName
in interfaceSharedSessionContractImplementor
-
bestGuessEntityName
Description copied from interface:SharedSessionContractImplementor
Obtain the best estimate of the entity name of the given entity instance, which is not involved in an association, by also considering information held in the proxy, and whether the object is already associated with this session.- Specified by:
bestGuessEntityName
in interfaceSharedSessionContractImplementor
-
getEntityName
Description copied from interface:Session
Return the entity name for a persistent entity.- Specified by:
getEntityName
in interfaceSession
- Parameters:
object
- a persistent entity associated with this session- Returns:
- the entity name
-
getReference
public <T> T getReference(T object) Description copied from interface:Session
Return a reference to the persistent instance with the same identity as the given instance, which might be detached, making the assumption that the instance is still persistent in the database. This method never results in access to the underlying data store, and thus might return a proxy that is initialized on-demand, when a non-identifier method is accessed.- Specified by:
getReference
in interfaceEntityManager
- Specified by:
getReference
in interfaceSession
- Parameters:
object
- a detached persistent instance- Returns:
- the persistent instance or proxy
-
guessEntityName
Description copied from interface:SharedSessionContractImplementor
Obtain an estimate of the entity name of the given entity instance, which is not involved in an association, using only theEntityNameResolver
.- Specified by:
guessEntityName
in interfaceSharedSessionContractImplementor
-
cancelQuery
public void cancelQuery()Description copied from interface:Session
Cancel the execution of the current query.This is the sole method on session which may be safely called from another thread.
- Specified by:
cancelQuery
in interfaceSession
-
toString
-
getActionQueue
Description copied from interface:SessionImplementor
Get theActionQueue
associated with this session.- Specified by:
getActionQueue
in interfaceEventSource
- Specified by:
getActionQueue
in interfaceSessionImplementor
-
getPersistenceContext
Description copied from interface:SharedSessionContractImplementor
Get the persistence context for this session.See
SharedSessionContractImplementor.getPersistenceContextInternal()
for a faster alternative.- Specified by:
getPersistenceContext
in interfaceSharedSessionContractImplementor
-
getPersistenceContextInternal
Description copied from interface:SharedSessionContractImplementor
Similar toSharedSessionContractImplementor.getPersistenceContext()
, with two differences:- this version performs better as it allows for inlining and probably better prediction, and
- it skips some checks of the current state of the session.
- Specified by:
getPersistenceContextInternal
in interfaceSharedSessionContractImplementor
- Returns:
- the
PersistenceContext
associated to this session.
-
getStatistics
Description copied from interface:Session
Get the statistics for this session.- Specified by:
getStatistics
in interfaceSession
- Returns:
- the session statistics being collected for this session
-
isEventSource
public boolean isEventSource()Description copied from interface:SharedSessionContractImplementor
Determines if this session implementsEventSource
.Only stateful session are sources of events. If this object is a stateless session, this method return
false
.- Specified by:
isEventSource
in interfaceSharedSessionContractImplementor
-
asEventSource
Description copied from interface:SharedSessionContractImplementor
Cast this session toEventSource
if possible.Only stateful session are sources of events. If this object is a stateless session, this method throws.
- Specified by:
asEventSource
in interfaceSharedSessionContractImplementor
-
isDefaultReadOnly
public boolean isDefaultReadOnly()Description copied from interface:SharedSessionContractImplementor
Are entities and proxies loaded by this session read-only by default?- Specified by:
isDefaultReadOnly
in interfaceSession
- Specified by:
isDefaultReadOnly
in interfaceSharedSessionContractImplementor
- Returns:
true
, loaded entities/proxies will be made read-only by default;false
, loaded entities/proxies will be made modifiable by default.- See Also:
-
setDefaultReadOnly
public void setDefaultReadOnly(boolean defaultReadOnly) Description copied from interface:Session
Change the default for entities and proxies loaded into this session 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 session's current setting.
To change the read-only/modifiable setting for a particular entity or proxy that already belongs to this session use
Session.setReadOnly(Object, boolean)
.To override this session's read-only/modifiable setting for all entities and proxies loaded by a certain
Query
useQuery.setReadOnly(boolean)
.- Specified by:
setDefaultReadOnly
in interfaceSession
- Parameters:
defaultReadOnly
-true
, the default for loaded entities/proxies is read-only;false
, the default for loaded entities/proxies is modifiable- See Also:
-
isReadOnly
Description copied from interface:Session
Is the specified entity or proxy read-only?To get the default read-only/modifiable setting used for entities and proxies that are loaded into the session use
Session.isDefaultReadOnly()
- Specified by:
isReadOnly
in interfaceSession
- Parameters:
entityOrProxy
- an entity or proxy- Returns:
true
if the entity or proxy is read-only,false
if the entity or proxy is modifiable.- See Also:
-
setReadOnly
Description copied from interface:Session
Set an unmodified persistent object to read-only mode, or a read-only object to modifiable mode. In read-only mode, no snapshot is maintained, the instance is never dirty checked, and changes are not persisted.If the entity or proxy already has the specified read-only/modifiable setting, then this method does nothing.
To set the default read-only/modifiable setting used for all entities and proxies that are loaded into the session use
Session.setDefaultReadOnly(boolean)
.To override this session's read-only/modifiable setting for entities and proxies loaded by a
Query
useQuery.setReadOnly(boolean)
- Specified by:
setReadOnly
in interfaceSession
- Parameters:
entity
- an entity or proxyreadOnly
-true
if the entity or proxy should be made read-only;false
if the entity or proxy should be made modifiable- See Also:
-
getCacheStoreMode
Description copied from interface:Session
The JPA-definedCacheStoreMode
.- Specified by:
getCacheStoreMode
in interfaceEntityManager
- Specified by:
getCacheStoreMode
in interfaceSession
- See Also:
-
getCacheRetrieveMode
Description copied from interface:Session
The JPA-definedCacheRetrieveMode
.- Specified by:
getCacheRetrieveMode
in interfaceEntityManager
- Specified by:
getCacheRetrieveMode
in interfaceSession
- See Also:
-
setCacheStoreMode
Description copied from interface:Session
Enable or disable writes to the second-level cache.- Specified by:
setCacheStoreMode
in interfaceEntityManager
- Specified by:
setCacheStoreMode
in interfaceSession
- Parameters:
cacheStoreMode
- a JPA-definedCacheStoreMode
- See Also:
-
setCacheRetrieveMode
Description copied from interface:Session
Enable or disable reads from the second-level cache.- Specified by:
setCacheRetrieveMode
in interfaceEntityManager
- Specified by:
setCacheRetrieveMode
in interfaceSession
- Parameters:
cacheRetrieveMode
- a JPA-definedCacheRetrieveMode
- See Also:
-
afterScrollOperation
public void afterScrollOperation()Description copied from interface:SharedSessionContractImplementor
Called after each operation on aScrollableResults
, providing an opportunity for a stateless session to clear its temporary persistence context. For a stateful session, this method does nothing.- Specified by:
afterScrollOperation
in interfaceSharedSessionContractImplementor
-
getLoadQueryInfluencers
Description copied from interface:SharedSessionContractImplementor
Get theLoadQueryInfluencers
associated with this session.- Specified by:
getLoadQueryInfluencers
in interfaceSharedSessionContractImplementor
- Returns:
- the
LoadQueryInfluencers
associated with this session; should never be null.
-
isFetchProfileEnabled
Description copied from interface:Session
Is thefetch profile
with the given name enabled in this session?- Specified by:
isFetchProfileEnabled
in interfaceSession
- Parameters:
name
- the name of the profile- Returns:
- True if fetch profile is enabled; false if not.
- Throws:
UnknownProfileException
- Indicates that the given name does not match any known fetch profile names- See Also:
-
enableFetchProfile
Description copied from interface:Session
Enable thefetch profile
with the given name in this session. If the requested fetch profile is already enabled, the call has no effect.- Specified by:
enableFetchProfile
in interfaceSession
- Parameters:
name
- the name of the fetch profile to be enabled- Throws:
UnknownProfileException
- Indicates that the given name does not match any known fetch profile names- See Also:
-
disableFetchProfile
Description copied from interface:Session
Disable thefetch profile
with the given name in this session. If the requested fetch profile is not currently enabled, the call has no effect.- Specified by:
disableFetchProfile
in interfaceSession
- Parameters:
name
- the name of the fetch profile to be disabled- Throws:
UnknownProfileException
- Indicates that the given name does not match any known fetch profile names- See Also:
-
setSubselectFetchingEnabled
public void setSubselectFetchingEnabled(boolean enabled) Description copied from interface:Session
Enable or disable subselect fetching in this session. Override the factory-level default controlled by the configuration property "hibernate.use_subselect_fetch".- Specified by:
setSubselectFetchingEnabled
in interfaceSession
- Parameters:
enabled
-true
to enable subselect fetching- See Also:
-
isSubselectFetchingEnabled
public boolean isSubselectFetchingEnabled()Description copied from interface:Session
Determine if subselect fetching is enabled in this session.- Specified by:
isSubselectFetchingEnabled
in interfaceSession
- Returns:
true
is subselect fetching is enabled
-
setFetchBatchSize
public void setFetchBatchSize(int batchSize) Description copied from interface:Session
Set the maximum batch size for batch fetching associations by id in this session. Override the factory-level default controlled by the configuration property "hibernate.default_batch_fetch_size".- If
batchSize>1
, then batch fetching is enabled. - If
batchSize<0
, the batch size is inherited from the factory-level setting. - Otherwise, batch fetching is disabled.
- Specified by:
setFetchBatchSize
in interfaceSession
- Parameters:
batchSize
- the maximum batch size for batch fetching- See Also:
- If
-
getFetchBatchSize
public int getFetchBatchSize()Description copied from interface:Session
Get the maximum batch size for batch fetching associations by id in this session.- Specified by:
getFetchBatchSize
in interfaceSession
-
getLobHelper
Description copied from interface:Session
- Specified by:
getLobHelper
in interfaceSession
- Returns:
- an instance of
LobHelper
-
beforeTransactionCompletion
public void beforeTransactionCompletion()Description copied from interface:JdbcSessionOwner
A before-completion callback to the owner.- Specified by:
beforeTransactionCompletion
in interfaceJdbcSessionOwner
- Overrides:
beforeTransactionCompletion
in classAbstractSharedSessionContract
-
afterTransactionCompletion
public void afterTransactionCompletion(boolean successful, boolean delayed) Description copied from interface:JdbcSessionOwner
An after-completion callback to the owner.- Specified by:
afterTransactionCompletion
in interfaceJdbcSessionOwner
- Overrides:
afterTransactionCompletion
in classAbstractSharedSessionContract
- Parameters:
successful
- Was the transaction successful?delayed
- Is this a delayed after transaction completion call (aka after a timeout)?
-
startTransactionBoundary
public void startTransactionBoundary()Description copied from interface:JdbcSessionOwner
Callback indicating recognition of entering into a transactional context whether that is explicitly via the HibernateTransaction
API or via registration of Hibernate's JTA Synchronization impl with a JTA Transaction- Specified by:
startTransactionBoundary
in interfaceJdbcSessionOwner
- Overrides:
startTransactionBoundary
in classAbstractSharedSessionContract
-
afterTransactionBegin
public void afterTransactionBegin()Description copied from interface:JdbcSessionOwner
An after-begin callback from the coordinator to its owner.- Specified by:
afterTransactionBegin
in interfaceJdbcSessionOwner
-
flushBeforeTransactionCompletion
public void flushBeforeTransactionCompletion()- Specified by:
flushBeforeTransactionCompletion
in interfaceJdbcSessionOwner
-
getSession
Description copied from interface:SharedSessionContractImplementor
Returns this object, fulfilling the contract ofWrapperOptions
.- Specified by:
getSession
in interfaceLoadAccessContext
- Specified by:
getSession
in interfaceSessionImplementor
- Specified by:
getSession
in interfaceSharedSessionContractImplementor
- Specified by:
getSession
in interfaceWrapperOptions
-
remove
Description copied from interface:Session
Mark a persistence instance associated with this session for removal from the underlying database. Ths operation cascades to associated instances if the association is mappedCascadeType.REMOVE
.Except when operating in fully JPA-compliant mode, this operation does, contrary to the JPA specification, accept a detached entity instance.
- Specified by:
remove
in interfaceEntityManager
- Specified by:
remove
in interfaceSession
- Parameters:
entity
- the managed persistent instance to remove, or a detached instance unless operating in fully JPA-compliant mode
-
find
Description copied from interface:Session
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.The object returned by
get()
orfind()
is either an unproxied instance of the given entity class, or a fully-fetched proxy object.This operation requests
LockMode.NONE
, that is, no lock, allowing the object to be retrieved from the cache without the cost of database access. However, if it is necessary to read the state from the database, the object will be returned with the lock modeLockMode.READ
.To bypass the second-level cache, and ensure that the state of the requested instance is read directly from the database, either:
- call
EntityManager.find(Class, Object, FindOption...)
, passingCacheRetrieveMode.BYPASS
as an option, - call
Session.find(Class, Object, LockMode)
with the explicit lock modeLockMode.READ
, or - set the cache mode to
CacheRetrieveMode.BYPASS
before calling this method.
- Specified by:
find
in interfaceEntityManager
- Specified by:
find
in interfaceSession
- Parameters:
entityClass
- the entity typeprimaryKey
- an identifier- Returns:
- a fully-fetched persistent instance or null
- call
-
find
- Specified by:
find
in interfaceEntityManager
-
find
- Specified by:
find
in interfaceEntityManager
-
find
Description copied from interface:Session
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance. Obtain the specified lock mode if the instance exists.Convenient form of
Session.find(Class, Object, LockOptions)
. -
find
Description copied from interface:Session
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance. Obtain the specified lock mode if the instance exists. -
find
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockModeType, Map<String, Object> properties) - Specified by:
find
in interfaceEntityManager
-
find
- Specified by:
find
in interfaceEntityManager
-
find
- Specified by:
find
in interfaceEntityManager
-
determineAppropriateLocalCacheMode
-
getReference
Description copied from interface:Session
Return a reference to the persistent instance with the given class and identifier, making the assumption that the instance is still persistent in the database. This method never results in access to the underlying data store, and thus might return a proxy that is initialized on-demand, when a non-identifier method is accessed.Note that
Hibernate.createDetachedProxy(SessionFactory, Class, Object)
may be used to obtain a detached reference.It's sometimes necessary to narrow a reference returned by
getReference()
to a subtype of the given entity type. A direct Java typecast should never be used in this situation. Instead, the methodHibernate.unproxy(Object, Class)
is the recommended way to narrow the type of a proxy object. Alternatively, a new reference may be obtained by simply callinggetReference()
again, passing the subtype. Either way, the narrowed reference will usually not be identical to the original reference, when the references are compared using the==
operator.- Specified by:
getReference
in interfaceEntityManager
- Specified by:
getReference
in interfaceSession
- Parameters:
entityClass
- the entity typeid
- the identifier of a persistent instance that exists in the database- Returns:
- the persistent instance or proxy
-
getReference
Description copied from interface:Session
Return a reference to the persistent instance of the given named entity with the given identifier, making the assumption that the instance is still persistent in the database. This method never results in access to the underlying data store, and thus might return a proxy that is initialized on-demand, when a non-identifier method is accessed.- Specified by:
getReference
in interfaceSession
- Parameters:
entityName
- the entity nameid
- the identifier of a persistent instance that exists in the database- Returns:
- the persistent instance or proxy
-
lock
- Specified by:
lock
in interfaceEntityManager
-
lock
- Specified by:
lock
in interfaceEntityManager
-
lock
- Specified by:
lock
in interfaceEntityManager
-
refresh
- Specified by:
refresh
in interfaceEntityManager
-
refresh
- Specified by:
refresh
in interfaceEntityManager
-
refresh
- Specified by:
refresh
in interfaceEntityManager
-
refresh
- Specified by:
refresh
in interfaceEntityManager
-
detach
Description copied from interface:Session
Remove this instance from the session cache. Changes to the instance will not be synchronized with the database. This operation cascades to associated instances if the association is mapped withCascadeType.DETACH
.- Specified by:
detach
in interfaceEntityManager
- Specified by:
detach
in interfaceSession
- Parameters:
entity
- the managed instance to detach
-
getLockMode
- Specified by:
getLockMode
in interfaceEntityManager
-
setProperty
- Specified by:
setProperty
in interfaceEntityManager
-
getProperties
- Specified by:
getProperties
in interfaceEntityManager
-
createNamedStoredProcedureQuery
Description copied from interface:SharedSessionContract
Obtain aProcedureCall
based on a named template- Specified by:
createNamedStoredProcedureQuery
in interfaceEntityManager
- Specified by:
createNamedStoredProcedureQuery
in interfaceSharedSessionContract
- Overrides:
createNamedStoredProcedureQuery
in classAbstractSharedSessionContract
- Parameters:
name
- The name given to the template- Returns:
- The ProcedureCall
- See Also:
-
createStoredProcedureQuery
Description copied from interface:SharedSessionContract
Create aProcedureCall
to a stored procedure.- Specified by:
createStoredProcedureQuery
in interfaceEntityManager
- Specified by:
createStoredProcedureQuery
in interfaceSharedSessionContract
- Overrides:
createStoredProcedureQuery
in classAbstractSharedSessionContract
- Parameters:
procedureName
- The name of the procedure.- Returns:
- The representation of the procedure call.
-
createStoredProcedureQuery
Description copied from interface:SharedSessionContract
Create aProcedureCall
to a stored procedure with the given result set entity mappings. Each given class is considered a "root return".- Specified by:
createStoredProcedureQuery
in interfaceEntityManager
- Specified by:
createStoredProcedureQuery
in interfaceSharedSessionContract
- Overrides:
createStoredProcedureQuery
in classAbstractSharedSessionContract
- Parameters:
procedureName
- The name of the procedure.resultClasses
- The entity(s) to map the result on to.- Returns:
- The representation of the procedure call.
-
createStoredProcedureQuery
Description copied from interface:SharedSessionContract
Create aProcedureCall
to a stored procedure with the given result set entity mappings.- Specified by:
createStoredProcedureQuery
in interfaceEntityManager
- Specified by:
createStoredProcedureQuery
in interfaceSharedSessionContract
- Overrides:
createStoredProcedureQuery
in classAbstractSharedSessionContract
- Parameters:
procedureName
- The name of the procedure.resultSetMappings
- The explicit result set mapping(s) to use for mapping the results- Returns:
- The representation of the procedure call.
-
unwrap
- Specified by:
unwrap
in interfaceEntityManager
-
getDelegate
- Specified by:
getDelegate
in interfaceEntityManager
-
getEntityManagerFactory
- Specified by:
getEntityManagerFactory
in interfaceEntityManager
-
getMetamodel
- Specified by:
getMetamodel
in interfaceEntityManager
-