Interface Session
- All Superinterfaces:
AutoCloseable,EntityManager,QueryProducer,Serializable,SharedSessionContract
- All Known Subinterfaces:
EventSource,SessionImplementor
- All Known Implementing Classes:
SessionDelegatorBaseImpl,SessionImpl,SessionLazyDelegator
The lifecycle of a Session is bounded by the beginning and end of the logical
transaction. But a long logical transaction might span several database transactions.
The primary purpose of the Session is to offer create, read, and delete
operations for instances of mapped entity classes. An instance may be in one of three
states with respect to a given open session:
- transient: never persistent, and not associated with the
Session, - persistent: currently associated with the
Session, or - detached: previously persistent, but not currently associated with the
Session.
At any given time, an instance may be associated with at most one open session.
Any instance returned by get(Class, Object), EntityManager.find(Class, Object),
or by a query is persistent. A persistent instance might hold references to other
entity instances, and sometimes these references are proxied by an
intermediate object. When an associated entity has not yet been fetched from the
database, references to the unfetched entity are represented by uninitialized
proxies. The state of an unfetched entity is automatically fetched from the
database when a method of its proxy is invoked, if and only if the proxy is
associated with an open session. Otherwise, getReference(Object) may be
used to trade a proxy belonging to a closed session for a new proxy associated
with the current session.
A transient instance may be made persistent by calling persist(Object).
A persistent instance may be made detached by calling detach(Object).
A persistent instance may be marked for removal, and eventually made transient, by
calling remove(Object).
Persistent instances are held in a managed state by the persistence context. Any
change to the state of a persistent instance is automatically detected and eventually
flushed to the database. This process of automatic change detection is called
dirty checking and can be expensive in some circumstances. Dirty checking
may be disabled by marking an entity as read-only using
setReadOnly(Object, boolean) or simply by evicting
it from the persistence context. A session may be set to load entities as read-only
by default, or this may be controlled at the
query level.
The state of a transient or detached instance may be made persistent by copying it to
a persistent instance using merge(Object). All older operations which moved a
detached instance to the persistent state are now deprecated, and clients should now
migrate to the use of merge().
The persistent state of a managed entity may be refreshed from the database, discarding
all modifications to the object held in memory, by calling refresh(Object).
From time to time, a flush operation is
triggered, and the session synchronizes state held in memory with persistent state
held in the database by executing SQL insert, update, and delete
statements. Note that SQL statements are often not executed synchronously by the methods
of the Session interface. If synchronous execution of SQL is desired, the
StatelessSession allows this.
Each managed instance has an associated LockMode. By default, the session
obtains only LockMode.READ on an entity instance it reads from the database
and LockMode.WRITE on an entity instance it writes to the database. This
behavior is appropriate for programs which use optimistic locking.
- A different lock level may be obtained by explicitly specifying the mode using
get(Class, Object, LockMode),EntityManager.find(Class, Object, LockModeType),refresh(Object, LockMode),EntityManager.refresh(Object, LockModeType), orSelectionQuery.setLockMode(LockModeType). - The lock level of a managed instance already held by the session may be upgraded
to a more restrictive lock level by calling
lock(Object, LockMode)orEntityManager.lock(Object, LockModeType).
A persistence context holds hard references to all its entities and prevents them
from being garbage collected. Therefore, a Session is a short-lived object,
and must be discarded as soon as a logical transaction ends. In extreme cases,
clear() and detach(Object) may be used to control memory usage.
However, for processes which read many entities, a StatelessSession should
be used.
A session might be associated with a container-managed JTA transaction, or it might be
in control of its own resource-local database transaction. In the case of a
resource-local transaction, the client must demarcate the beginning and end of the
transaction using a Transaction. A typical resource-local transaction should
use the following idiom:
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
//do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
session.close();
}
It's crucially important to appreciate the following restrictions and why they exist:
- If the
Sessionthrows an exception, the current transaction must be rolled back and the session must be discarded. The internal state of theSessioncannot be expected to be consistent with the database after the exception occurs. - At the end of a logical transaction, the session must be explicitly destroyed, so that all JDBC resources may be released.
- A
Sessionis never thread-safe. It contains various different sorts of fragile mutable state. Each thread or transaction must obtain its own dedicated instance from theSessionFactory.
An easy way to be sure that session and transaction management is being done correctly is to let the factory do it:
sessionFactory.inTransaction(session -> {
//do the work
...
});
A session may be used to execute JDBC work using its JDBC connection and transaction:
session.doWork(connection -> {
try ( PreparedStatement ps = connection.prepareStatement( " ... " ) ) {
ps.execute();
}
});
A Session instance is serializable if its entities are serializable.
Every Session is a JPA EntityManager. Furthermore, when Hibernate is
acting as the JPA persistence provider, the method EntityManager.unwrap(Class)
may be used to obtain the underlying Session.
Hibernate, unlike JPA, allows a persistence unit where an entity class is mapped multiple
times, with different entity names, usually to different tables. In this case, the session
needs a way to identify the entity name of a given instance of the entity class. Therefore,
some operations of this interface, including operations inherited from EntityManager,
are overloaded with a form that accepts an explicit entity name along with the instance. An
alternative solution to this problem is to provide an EntityNameResolver.
- See Also:
-
Nested Class Summary
Nested Classes -
Method Summary
Modifier and TypeMethodDescriptionvoidaddEventListeners(SessionEventListener... listeners) Add one or more listeners to the SessionbuildLockRequest(LockOptions lockOptions) Deprecated.<T> IdentifierLoadAccess<T>Create anIdentifierLoadAccessinstance to retrieve an instance of the given entity type by its primary key.<T> IdentifierLoadAccess<T>Create anIdentifierLoadAccessinstance to retrieve an instance of the named entity type by its primary key.<T> MultiIdentifierLoadAccess<T>byMultipleIds(Class<T> entityClass) Create aMultiIdentifierLoadAccessinstance to retrieve multiple instances of the given entity type by their primary key values, using batching.<T> MultiIdentifierLoadAccess<T>byMultipleIds(String entityName) Create aMultiIdentifierLoadAccessinstance to retrieve multiple instances of the named entity type by their primary key values, using batching.<T> NaturalIdMultiLoadAccess<T>byMultipleNaturalId(Class<T> entityClass) Create aMultiIdentifierLoadAccessinstance to retrieve multiple instances of the given entity type by their by natural id values, using batching.<T> NaturalIdMultiLoadAccess<T>byMultipleNaturalId(String entityName) Create aMultiIdentifierLoadAccessinstance 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 aNaturalIdLoadAccessinstance 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 aNaturalIdLoadAccessinstance 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 aSimpleNaturalIdLoadAccessinstance 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 aSimpleNaturalIdLoadAccessinstance to retrieve an instance of the named entity type by its natural id, which must be a simple (non-composite) value.default <C,T> T callWithConnection(ConnectionFunction<C, T> function) voidCancel the execution of the current query.voidclear()Completely clear the session.booleanDetermine if the given entity is associated with this session.<T> RootGraph<T>createEntityGraph(Class<T> rootType) Create a new mutableEntityGraphwith only a root node.RootGraph<?>createEntityGraph(String graphName) Create a new mutable copy of the namedEntityGraph, or returnnullif there is no graph with the given name.createNamedQuery(String name) Deprecated.<R> Query<R>createNamedQuery(String name, Class<R> resultClass) Create a typedQueryinstance for the given named query.createQuery(CriteriaDelete deleteQuery) Deprecated.<R> Query<R>createQuery(CriteriaQuery<R> criteriaQuery) Create aQueryfor the given JPACriteriaQuery.createQuery(CriteriaUpdate updateQuery) Deprecated.<R> Query<R>createQuery(TypedQueryReference<R> typedQueryReference) Create a typedQueryinstance for the given typed query reference.createQuery(String queryString) Deprecated.<R> Query<R>createQuery(String queryString, Class<R> resultClass) Create a typedQueryinstance for the given HQL query string and given query result type.voidRemove this instance from the session cache.voiddisableFetchProfile(String name) Disable thefetch profilewith the given name in this session.voiddisableFilter(String filterName) Disable the named filter for the current session.voidenableFetchProfile(String name) Enable thefetch profilewith the given name in this session.enableFilter(String filterName) Enable the named filter for this current session.voidRemove this instance from the session cache.voidflush()Force this session to flush.<T> TReturn the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.<T> TReturn the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.<T> Tget(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.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 the current cache mode for this session.The JPA-definedCacheRetrieveMode.The JPA-definedCacheStoreMode.getCurrentLockMode(Object object) Determine the currentLockModeof the given managed instance associated with this session.getEnabledFilter(String filterName) Retrieve a currently enabled filter by name.RootGraph<?>getEntityGraph(String graphName) Retrieve the namedEntityGraphas an immutable graph, or returnnullif there is no graph with the given name.<T> List<EntityGraph<? super T>>getEntityGraphs(Class<T> entityClass) Retrieve all namedEntityGraphs with the given type.getEntityName(Object object) Return the entity name for a persistent entity.intGet the maximum batch size for batch fetching associations by id in this session.Get the current JPA flush mode for this session.Get the current flush mode for this session.getIdentifier(Object object) Return the identifier value of the given entity associated with this session.<T> TgetReference(Class<T> entityType, 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> TgetReference(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.Get the session factory which created this session.Get the statistics for this session.booleanWill entities and proxies that are loaded into this session be made read-only by default?booleanisDirty()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?booleanisFetchProfileEnabled(String name) Is thefetch profilewith the given name enabled in this session?booleanisReadOnly(Object entityOrProxy) Is the specified entity or proxy read-only?booleanDetermine if subselect fetching is enabled in this session.<T> TDeprecated.<T> TDeprecated.<T> Tload(Class<T> theClass, Object id, LockOptions lockOptions) Deprecated.voidRead the persistent state associated with the given identifier into the given transient instance.Deprecated.Deprecated.load(String entityName, Object id, LockOptions lockOptions) Deprecated.voidObtain the specified lock level on the given managed instance associated with this session.voidlock(Object object, LockOptions lockOptions) Obtain a lock on the given managed instance associated with this session, using the given lock options.voidDeprecated.<T> TCopy the state of the given object onto the persistent object with the same identifier.<T> Tmerge(T object) Copy the state of the given object onto the persistent object with the same identifier.voidMake a transient instance persistent and mark it for later insertion in the database.voidMake a transient instance persistent and mark it for later insertion in the database.voidReread the state of the given managed instance associated with this session from the underlying database.voidReread the state of the given managed instance from the underlying database, obtaining the givenLockMode.voidrefresh(Object object, LockOptions lockOptions) Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode.voidMark a persistence instance associated with this session for removal from the underlying database.voidreplicate(Object object, ReplicationMode replicationMode) Deprecated.With no real replacementvoidreplicate(String entityName, Object object, ReplicationMode replicationMode) Deprecated.With no real replacementdefault <C> voidrunWithConnection(ConnectionConsumer<C> action) Obtain aSessionbuilder with the ability to copy certain information from this session.voidsetCacheMode(CacheMode cacheMode) Set the current cache mode for this session.voidsetCacheRetrieveMode(CacheRetrieveMode cacheRetrieveMode) Enable or disable reads from the second-level cache.voidsetCacheStoreMode(CacheStoreMode cacheStoreMode) Enable or disable writes to the second-level cache.voidsetDefaultReadOnly(boolean readOnly) Change the default for entities and proxies loaded into this session from modifiable to read-only mode, or from modifiable to read-only mode.voidsetFetchBatchSize(int batchSize) Set the maximum batch size for batch fetching associations by id in this session.voidsetFlushMode(FlushModeType flushMode) Set the currentJPA flush modefor this session.voidsetHibernateFlushMode(FlushMode flushMode) Set the current flush mode for this session.voidsetReadOnly(Object entityOrProxy, boolean readOnly) Set an unmodified persistent object to read-only mode, or a read-only object to modifiable mode.voidsetSubselectFetchingEnabled(boolean enabled) Enable or disable subselect fetching in this session.Methods inherited from interface jakarta.persistence.EntityManager
close, contains, createNamedStoredProcedureQuery, createNativeQuery, createNativeQuery, createNativeQuery, createQuery, createStoredProcedureQuery, createStoredProcedureQuery, createStoredProcedureQuery, find, find, find, find, find, find, getCriteriaBuilder, getDelegate, getEntityManagerFactory, getLockMode, getMetamodel, getProperties, getTransaction, isJoinedToTransaction, isOpen, joinTransaction, lock, lock, lock, refresh, refresh, refresh, refresh, setProperty, unwrapMethods inherited from interface org.hibernate.query.QueryProducer
createMutationQuery, createMutationQuery, createMutationQuery, createMutationQuery, createMutationQuery, createNamedMutationQuery, createNamedSelectionQuery, createNamedSelectionQuery, createNativeMutationQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createSelectionQuery, createSelectionQuery, createSelectionQuery, getNamedNativeQuery, getNamedNativeQuery, getNamedQueryMethods inherited from interface org.hibernate.SharedSessionContract
beginTransaction, close, createEntityGraph, createNamedStoredProcedureQuery, createStoredProcedureCall, createStoredProcedureCall, createStoredProcedureCall, createStoredProcedureQuery, createStoredProcedureQuery, createStoredProcedureQuery, doReturningWork, doWork, getCriteriaBuilder, getFactory, getJdbcBatchSize, getNamedProcedureCall, getTenantIdentifier, getTenantIdentifierValue, getTransaction, isConnected, isJoinedToTransaction, isOpen, joinTransaction, setJdbcBatchSize
-
Method Details
-
flush
void flush()Force this session to flush. Must be called at the end of a unit of work, before the transaction is committed. Depending on the current flush mode, the session might automatically flush whenEntityTransaction.commit()is called, and it is not necessary to call this method directly.Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.
- Specified by:
flushin interfaceEntityManager- Throws:
HibernateException- if changes could not be synchronized with the database
-
setFlushMode
Set the currentJPA flush modefor 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:
setFlushModein interfaceEntityManager- Parameters:
flushMode- the newFlushModeType- See Also:
-
setHibernateFlushMode
Set the current 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.
The default flush mode is sometimes unnecessarily aggressive. For a logically "read only" session, it's reasonable to set the session's flush mode to
FlushMode.MANUALat the start of the session in order to avoid some unnecessary work.Note that
FlushModedefines more options thanFlushModeType.- Parameters:
flushMode- the newFlushMode
-
getFlushMode
FlushModeType getFlushMode()Get the current JPA flush mode for this session.- Specified by:
getFlushModein interfaceEntityManager- Returns:
- the
FlushModeTypecurrently in effect
-
getHibernateFlushMode
FlushMode getHibernateFlushMode()Get the current flush mode for this session.- Returns:
- the
FlushModecurrently in effect
-
setCacheMode
Set the current cache mode for this session.The cache mode determines the manner in which this session can interact with the second level cache.
- Parameters:
cacheMode- the new cache mode
-
getCacheMode
CacheMode getCacheMode()Get the current cache mode for this session.- Returns:
- the current cache mode
-
getCacheStoreMode
CacheStoreMode getCacheStoreMode()The JPA-definedCacheStoreMode.- Specified by:
getCacheStoreModein interfaceEntityManager- Since:
- 6.2
- See Also:
-
getCacheRetrieveMode
CacheRetrieveMode getCacheRetrieveMode()The JPA-definedCacheRetrieveMode.- Specified by:
getCacheRetrieveModein interfaceEntityManager- Since:
- 6.2
- See Also:
-
setCacheStoreMode
Enable or disable writes to the second-level cache.- Specified by:
setCacheStoreModein interfaceEntityManager- Parameters:
cacheStoreMode- a JPA-definedCacheStoreMode- Since:
- 6.2
- See Also:
-
setCacheRetrieveMode
Enable or disable reads from the second-level cache.- Specified by:
setCacheRetrieveModein interfaceEntityManager- Parameters:
cacheRetrieveMode- a JPA-definedCacheRetrieveMode- Since:
- 6.2
- See Also:
-
getFetchBatchSize
int getFetchBatchSize()Get the maximum batch size for batch fetching associations by id in this session.- Since:
- 6.3
-
setFetchBatchSize
void setFetchBatchSize(int batchSize) 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.
- Parameters:
batchSize- the maximum batch size for batch fetching- Since:
- 6.3
- See Also:
- If
-
isSubselectFetchingEnabled
boolean isSubselectFetchingEnabled()Determine if subselect fetching is enabled in this session.- Returns:
trueis subselect fetching is enabled- Since:
- 6.3
-
setSubselectFetchingEnabled
void setSubselectFetchingEnabled(boolean enabled) Enable or disable subselect fetching in this session. Override the factory-level default controlled by the configuration property "hibernate.use_subselect_fetch".- Parameters:
enabled-trueto enable subselect fetching- Since:
- 6.3
- See Also:
-
getSessionFactory
SessionFactory getSessionFactory()Get the session factory which created this session.- Returns:
- the session factory
- See Also:
-
cancelQuery
void cancelQuery()Cancel the execution of the current query.This is the sole method on session which may be safely called from another thread.
- Throws:
HibernateException- if there was a problem cancelling the query
-
isDirty
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?- Returns:
trueif the session contains pending changes;falseotherwise.- Throws:
HibernateException- could not perform dirtying checking
-
isDefaultReadOnly
boolean isDefaultReadOnly()Will entities and proxies that are loaded into this session be made read-only by default?To determine the read-only/modifiable setting for a particular entity or proxy use
isReadOnly(Object).- 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
void setDefaultReadOnly(boolean readOnly) 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
setReadOnly(Object, boolean).To override this session's read-only/modifiable setting for all entities and proxies loaded by a certain
QueryuseQuery.setReadOnly(boolean).- Parameters:
readOnly-true, the default for loaded entities/proxies is read-only;false, the default for loaded entities/proxies is modifiable- See Also:
-
getIdentifier
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.- Parameters:
object- a persistent instance associated with this session- Returns:
- the identifier
- Throws:
TransientObjectException- if the instance is transient or associated with a different session
-
contains
Determine if the given entity is associated with this session.- Parameters:
entityName- the entity nameobject- an instance of a persistent class- Returns:
trueif the given instance is associated with thisSession
-
detach
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:
detachin interfaceEntityManager- Parameters:
object- the managed instance to detach
-
evict
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.This operation is a synonym for
detach(Object).- Parameters:
object- the managed entity to evict- Throws:
NullPointerException- if the passed object isnullIllegalArgumentException- if the passed object is not mapped as an entity
-
load
Deprecated.Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.Convenient form of
load(Class, Object, LockOptions).- Parameters:
theClass- a persistent classid- a valid identifier of an existing persistent instance of the classlockMode- the lock level- Returns:
- the persistent instance or proxy
- See Also:
-
load
Deprecated.Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.- Parameters:
theClass- a persistent classid- a valid identifier of an existing persistent instance of the classlockOptions- contains the lock level- Returns:
- the persistent instance or proxy
-
load
Deprecated.Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.Convenient form of
load(String, Object, LockOptions).- Parameters:
entityName- the entity nameid- a valid identifier of an existing persistent instance of the classlockMode- the lock level- Returns:
- the persistent instance or proxy
- See Also:
-
load
Deprecated.Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.- Parameters:
entityName- the entity nameid- a valid identifier of an existing persistent instance of the classlockOptions- contains the lock level- Returns:
- the persistent instance or proxy
-
load
Deprecated.Return the persistent instance of the given entity class with the given identifier, making the assumption that the instance exists in the database. This method might return a proxied instance that is initialized on-demand, when a non-identifier method is accessed.You should not use this method to determine if an instance exists in the database (use
get()instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.This operation is very similar to
getReference(Class, Object).- Parameters:
theClass- a persistent classid- a valid identifier of an existing persistent instance of the class- Returns:
- the persistent instance or proxy
-
load
Deprecated.Return the persistent instance of the given entity class with the given identifier, making the assumption that the instance exists in the database. This method might return a proxied instance that is initialized on-demand, when a non-identifier method is accessed.You should not use this method to determine if an instance exists in the database (use
get()instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.- Parameters:
entityName- the entity nameid- a valid identifier of an existing persistent instance of the class- Returns:
- the persistent instance or proxy
-
load
Read the persistent state associated with the given identifier into the given transient instance. -
replicate
Deprecated.With no real replacementPersist 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.- Parameters:
object- a detached instance of a persistent classreplicationMode- the replication mode to use
-
replicate
@Deprecated(since="6.0") void replicate(String entityName, Object object, ReplicationMode replicationMode) Deprecated.With no real replacementPersist 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.- Parameters:
entityName- the entity nameobject- a detached instance of a persistent classreplicationMode- the replication mode to use
-
merge
<T> T merge(T object) 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:
mergein interfaceEntityManager- Parameters:
object- a detached instance with state to be copied- Returns:
- an updated persistent instance
-
merge
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.- Parameters:
entityName- the entity nameobject- a detached instance with state to be copied- Returns:
- an updated persistent instance
-
persist
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:
persistin interfaceEntityManager- Parameters:
object- a transient instance to be made persistent
-
persist
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.- Parameters:
entityName- the entity nameobject- a transient instance to be made persistent
-
lock
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_READorLockMode.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.WRITEandLockMode.UPGRADE_SKIPLOCKEDare not legal arguments tolock().- Parameters:
object- a persistent instancelockMode- the lock level
- perform a version check on an entity read from the second-level cache
by requesting
-
lock
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.- Parameters:
object- a persistent instancelockOptions- the lock options- Since:
- 6.2
-
lock
Deprecated.Obtain the specified lock level on the given managed instance associated with this session. This may be used to:- perform a version check with
LockMode.READ, or - upgrade to a pessimistic lock with
LockMode.PESSIMISTIC_WRITE).
This operation cascades to associated instances if the association is mapped with
CascadeType.LOCK.- Parameters:
entityName- the name of the entityobject- a persistent instance associated with this sessionlockMode- the lock level
- perform a version check with
-
buildLockRequest
Deprecated.Build a new lock request that specifies:- the
LockModeto use, - the pessimistic lock timeout, and
- the scope that is, whether the lock extends to rows of owned collections.
Timeout and scope are ignored if the specified
LockModerepresents a flavor of optimistic locking.Call
Session.LockRequest.lock(Object)to actually obtain the requested lock on a managed entity instance.- Parameters:
lockOptions- contains the lock level- Returns:
- a
Session.LockRequestthat can be used to lock any given object.
- the
-
refresh
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
BloborClob.
This operation cascades to associated instances if the association is mapped with
CascadeType.REFRESH.This operation requests
LockMode.READ. To obtain a stronger lock, callrefresh(Object, LockMode).- Specified by:
refreshin interfaceEntityManager- Parameters:
object- a persistent instance associated with this session
-
refresh
Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode.Convenient form of
refresh(Object, LockOptions)- Parameters:
object- a persistent instance associated with this sessionlockMode- the lock mode to use- See Also:
-
refresh
Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode.- Parameters:
object- a persistent instance associated with this sessionlockOptions- contains the lock mode to use
-
remove
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.- Specified by:
removein interfaceEntityManager- Parameters:
object- the managed persistent instance to remove
-
getCurrentLockMode
Determine the currentLockModeof the given managed instance associated with this session.- Parameters:
object- a persistent instance associated with this session- Returns:
- the current lock mode
-
clear
void clear()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:
clearin interfaceEntityManager
-
get
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.This operation is very similar to
EntityManager.find(Class, Object).The object returned by
get()orfind()is either an unproxied instance of the given entity class, of 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
get(Class, Object, LockMode)with the explicit lock modeLockMode.READ, or - set the cache mode to
CacheMode.IGNOREbefore calling this method.
- Parameters:
entityType- the entity typeid- an identifier- Returns:
- a persistent instance or null
- call
-
get
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
get(Class, Object, LockOptions).This operation is very similar to
EntityManager.find(Class, Object, jakarta.persistence.LockModeType).- Parameters:
entityType- the entity typeid- an identifierlockMode- the lock mode- Returns:
- a persistent instance or null
- See Also:
-
get
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.- Parameters:
entityType- the entity typeid- an identifierlockOptions- the lock mode- Returns:
- a persistent instance or null
-
get
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.- Parameters:
entityName- the entity nameid- an identifier- Returns:
- a persistent instance or null
-
get
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
get(String, Object, LockOptions)- Parameters:
entityName- the entity nameid- an identifierlockMode- the lock mode- Returns:
- a persistent instance or null
- See Also:
-
get
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.- Parameters:
entityName- the entity nameid- an identifierlockOptions- contains the lock mode- Returns:
- a persistent instance or null
-
getEntityName
Return the entity name for a persistent entity.- Parameters:
object- a persistent entity associated with this session- Returns:
- the entity name
-
getReference
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:
getReferencein interfaceEntityManager- Parameters:
entityType- the entity typeid- the identifier of a persistent instance that exists in the database- Returns:
- the persistent instance or proxy
-
getReference
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.- Parameters:
entityName- the entity nameid- the identifier of a persistent instance that exists in the database- Returns:
- the persistent instance or proxy
-
getReference
<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. 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:
getReferencein interfaceEntityManager- Parameters:
object- a detached persistent instance- Returns:
- the persistent instance or proxy
- Since:
- 6.0
-
byId
Create anIdentifierLoadAccessinstance to retrieve an instance of the given entity type by its primary key.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- an instance of
IdentifierLoadAccessfor executing the lookup - Throws:
HibernateException- If the given class does not resolve as a mapped entity
-
byId
Create anIdentifierLoadAccessinstance to retrieve an instance of the named entity type by its primary key.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- an instance of
IdentifierLoadAccessfor executing the lookup - Throws:
HibernateException- If the given name does not resolve to a mapped entity
-
byMultipleIds
Create aMultiIdentifierLoadAccessinstance to retrieve multiple instances of the given entity type by their primary key values, using batching.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- an instance of
MultiIdentifierLoadAccessfor executing the lookup - Throws:
HibernateException- If the given class does not resolve as a mapped entity
-
byMultipleIds
Create aMultiIdentifierLoadAccessinstance to retrieve multiple instances of the named entity type by their primary key values, using batching.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- an instance of
MultiIdentifierLoadAccessfor executing the lookup - Throws:
HibernateException- If the given name does not resolve to a mapped entity
-
byNaturalId
Create aNaturalIdLoadAccessinstance 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.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- an instance of
NaturalIdLoadAccessfor executing the lookup - Throws:
HibernateException- If the given class does not resolve as a mapped entity, or if the entity does not declare a natural id
-
byNaturalId
Create aNaturalIdLoadAccessinstance 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.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- an instance of
NaturalIdLoadAccessfor executing the lookup - Throws:
HibernateException- If the given name does not resolve to a mapped entity, or if the entity does not declare a natural id
-
bySimpleNaturalId
Create aSimpleNaturalIdLoadAccessinstance 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.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- an instance of
SimpleNaturalIdLoadAccessfor executing the lookup - Throws:
HibernateException- If the given class does not resolve as a mapped entity, or if the entity does not declare a natural id
-
bySimpleNaturalId
Create aSimpleNaturalIdLoadAccessinstance 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.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- an instance of
SimpleNaturalIdLoadAccessfor executing the lookup - Throws:
HibernateException- If the given name does not resolve to a mapped entity, or if the entity does not declare a natural id
-
byMultipleNaturalId
Create aMultiIdentifierLoadAccessinstance to retrieve multiple instances of the given entity type by their by natural id values, using batching.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- an instance of
NaturalIdMultiLoadAccessfor executing the lookup - Throws:
HibernateException- If the given class does not resolve as a mapped entity, or if the entity does not declare a natural id
-
byMultipleNaturalId
Create aMultiIdentifierLoadAccessinstance to retrieve multiple instances of the named entity type by their by natural id values, using batching.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- an instance of
NaturalIdMultiLoadAccessfor executing the lookup - Throws:
HibernateException- If the given name does not resolve to a mapped entity, or if the entity does not declare a natural id
-
enableFilter
Description copied from interface:SharedSessionContractEnable the named filter for this current session.The returned
Filterobject must be used to bind arguments to parameters of the filter, and every parameter must be set before any other operation of this session is called.- Specified by:
enableFilterin interfaceSharedSessionContract- Parameters:
filterName- the name of the filter to be enabled.- Returns:
- the
Filterinstance representing the enabled filter. - See Also:
-
getEnabledFilter
Description copied from interface:SharedSessionContractRetrieve a currently enabled filter by name.- Specified by:
getEnabledFilterin interfaceSharedSessionContract- Parameters:
filterName- the name of the filter to be retrieved.- Returns:
- the
Filterinstance representing the enabled filter.
-
disableFilter
Description copied from interface:SharedSessionContractDisable the named filter for the current session.- Specified by:
disableFilterin interfaceSharedSessionContract- Parameters:
filterName- the name of the filter to be disabled.
-
getStatistics
SessionStatistics getStatistics()Get the statistics for this session.- Returns:
- the session statistics being collected for this session
-
isReadOnly
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
isDefaultReadOnly()- Parameters:
entityOrProxy- an entity or proxy- Returns:
trueif the entity or proxy is read-only,falseif the entity or proxy is modifiable.- See Also:
-
setReadOnly
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
setDefaultReadOnly(boolean).To override this session's read-only/modifiable setting for entities and proxies loaded by a
QueryuseQuery.setReadOnly(boolean)- Parameters:
entityOrProxy- an entity or proxyreadOnly-trueif the entity or proxy should be made read-only;falseif the entity or proxy should be made modifiable- See Also:
-
isFetchProfileEnabled
Is thefetch profilewith the given name enabled in this session?- 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
Enable thefetch profilewith the given name in this session. If the requested fetch profile is already enabled, the call has no effect.- 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
Disable thefetch profilewith the given name in this session. If the requested fetch profile is not currently enabled, the call has no effect.- 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:
-
getLobHelper
LobHelper getLobHelper()- Returns:
- an instance of
LobHelper
-
sessionWithOptions
SharedSessionBuilder sessionWithOptions()Obtain aSessionbuilder with the ability to copy certain information from this session.- Returns:
- the session builder
-
addEventListeners
Add one or more listeners to the Session- Parameters:
listeners- the listener(s) to add
-
createEntityGraph
Description copied from interface:SharedSessionContractCreate a new mutableEntityGraphwith only a root node.- Specified by:
createEntityGraphin interfaceEntityManager- Specified by:
createEntityGraphin interfaceSharedSessionContract- Parameters:
rootType- the root entity class of the graph
-
createEntityGraph
Description copied from interface:SharedSessionContractCreate a new mutable copy of the namedEntityGraph, or returnnullif there is no graph with the given name.- Specified by:
createEntityGraphin interfaceEntityManager- Specified by:
createEntityGraphin interfaceSharedSessionContract- Parameters:
graphName- the name of the graph- See Also:
-
getEntityGraph
Description copied from interface:SharedSessionContractRetrieve the namedEntityGraphas an immutable graph, or returnnullif there is no graph with the given name.- Specified by:
getEntityGraphin interfaceEntityManager- Specified by:
getEntityGraphin interfaceSharedSessionContract- Parameters:
graphName- the name of the graph- See Also:
-
getEntityGraphs
Description copied from interface:SharedSessionContractRetrieve all namedEntityGraphs with the given type.- Specified by:
getEntityGraphsin interfaceEntityManager- Specified by:
getEntityGraphsin interfaceSharedSessionContract- See Also:
-
createQuery
Description copied from interface:QueryProducerCreate a typedQueryinstance for the given HQL query string and given query result type.- If the query has a single item in the
selectlist, then the select item must be assignable to the given result type. - Otherwise, if there are multiple select items, then the
select items will be packaged into an instance of the
result type. The result type must have an appropriate
constructor with parameter types matching the select items,
or it must be one of the types
Object[],List,Map, orTuple.
If a query has no explicit
selectlist, the select list is inferred from the given query result type:- if the result type is an entity type, the query must have
exactly one root entity in the
fromclause, it must be assignable to the result type, and the inferred select list will contain just that entity, or - otherwise, the select list contains every root entity and
every non-
fetchjoined entity, and each query result will be packaged into an instance of the result type, just as specified above.
The returned
Querymay be executed by callingQuery.getResultList()orQuery.getSingleResult().- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer- Parameters:
queryString- The HQL queryresultClass- The type of the query result- Returns:
- The
Queryinstance for manipulation and execution - See Also:
- If the query has a single item in the
-
createQuery
Description copied from interface:QueryProducerCreate a typedQueryinstance for the given typed query reference.- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer- Parameters:
typedQueryReference- the type query reference- Returns:
- The
Queryinstance for execution - See Also:
-
createQuery
Deprecated.Description copied from interface:QueryProducerCreate aQueryinstance for the given HQL query, or HQL insert, update, or delete statement.If a query has no explicit
selectlist, the select list is inferred:- if there is exactly one root entity in the
fromclause, then that root entity is the only element of the select list, or - otherwise, if there are multiple root entities in the
fromclause, then the select list contains every root entity and every non-fetchjoined entity.
- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer- Parameters:
queryString- The HQL query- Returns:
- The
Queryinstance for manipulation and execution - See Also:
- if there is exactly one root entity in the
-
createNamedQuery
Description copied from interface:QueryProducerCreate a typedQueryinstance for the given named query. The named query might be defined in HQL or in native SQL.- Specified by:
createNamedQueryin interfaceEntityManager- Specified by:
createNamedQueryin interfaceQueryProducer- Parameters:
name- the name of a query defined in metadataresultClass- the type of the query result- Returns:
- The
Queryinstance for manipulation and execution - See Also:
-
createNamedQuery
Deprecated.Description copied from interface:QueryProducerCreate a typedQueryinstance for the given named query. The named query might be defined in HQL or in native SQL.- Specified by:
createNamedQueryin interfaceEntityManager- Specified by:
createNamedQueryin interfaceQueryProducer- Parameters:
name- the name of a predefined named query- Returns:
- The
Queryinstance for manipulation and execution - See Also:
-
createQuery
Description copied from interface:QueryProducerCreate aQueryfor the given JPACriteriaQuery.- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer
-
createQuery
Deprecated.Create aQueryfor the given JPACriteriaDelete.- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer
-
createQuery
Deprecated.Create aQueryfor the given JPACriteriaUpdate.- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer
-
runWithConnection
- Specified by:
runWithConnectionin interfaceEntityManager
-
callWithConnection
- Specified by:
callWithConnectionin interfaceEntityManager
-
LockOptionsand pass it tolock(Object, LockOptions).