Interface Session
-
- All Superinterfaces:
AutoCloseable,Closeable,EntityManager,QueryProducer,Serializable,SharedSessionContract
- All Known Subinterfaces:
EventSource,SessionImplementor
- All Known Implementing Classes:
SessionDelegatorBaseImpl
public interface Session extends SharedSessionContract, EntityManager
The main runtime interface between a Java application and Hibernate. Represents the notion of a persistence context, a set of managed entity instances associated with a logical transaction.The lifecycle of a
Sessionis 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
Sessionis 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 session:- transient: never persistent, not associated with any
Session, - persistent: associated with a unique
Session, or - detached: previously persistent, not associated with any
Session
get(Class, Object)or by a query is persistent.A transient instance may be made persistent by calling
persist(Object). A persistent instance may be made detached by callingdetach(Object). A persistent instance may be marked for removal, and eventually made transient, by callingremove(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 ofmerge().From
time to time, the session performs a flushing operation, and synchronizes state held in memory with persistent state held in the database by executing SQLinsert,update, anddeletestatements. Note that SQL statements are often not executed synchronously by the methods of theSessioninterface. If synchronous execution of SQL is desired, theStatelessSessionallows this.A persistence context holds hard references to all its entities and prevents them from being garbage collected. Therefore, a
Sessionis a short-lived object, and must be discarded as soon as a logical transaction ends. In extreme cases,clear()anddetach(Object)may be used to control memory usage. However, for processes which read many entities, aStatelessSessionshould be used.A
Sessionis never threadsafe. Each thread or transaction must obtain its own instance from aSessionFactory.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(); }If the
Sessionthrows an exception, the current transaction must be rolled back and the session must be discarded. The internal state of theSessionmight not be consistent with the database after the exception occurs.A
Sessioninstance is serializable if its entities are serializable.Every
Sessionis a JPAEntityManager. Furthermore, when Hibernate is acting as the JPA persistence provider, the methodEntityManager.unwrap(Class)may be used to obtain the underlyingSession.- See Also:
SessionFactory
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static interfaceSession.LockRequestContains locking details (LockMode, Timeout and Scope).
-
Method Summary
All Methods Instance Methods Abstract Methods Deprecated Methods Modifier and Type Method Description voidaddEventListeners(SessionEventListener... listeners)Add one or more listeners to the SessionSession.LockRequestbuildLockRequest(LockOptions lockOptions)Build a newlock requestthat specifies: theLockModeto use, the pessimistic lock timeout, and the scope of the lock.<T> IdentifierLoadAccess<T>byId(Class<T> entityClass)Create anIdentifierLoadAccessinstance to retrieve the specified entity by primary key.<T> IdentifierLoadAccess<T>byId(String entityName)Create anIdentifierLoadAccessinstance to retrieve the specified entity type by primary key.<T> MultiIdentifierLoadAccess<T>byMultipleIds(Class<T> entityClass)Create aMultiIdentifierLoadAccessinstance to retrieve multiple entities at once as specified by primary key values.<T> MultiIdentifierLoadAccess<T>byMultipleIds(String entityName)Create aMultiIdentifierLoadAccessinstance to retrieve multiple entities at once as specified by primary key values.<T> NaturalIdMultiLoadAccess<T>byMultipleNaturalId(Class<T> entityClass)Access to load multiple entities bynatural id.<T> NaturalIdMultiLoadAccess<T>byMultipleNaturalId(String entityName)Access to load multiple entities bynatural id.<T> NaturalIdLoadAccess<T>byNaturalId(Class<T> entityClass)Create aNaturalIdLoadAccessinstance to retrieve the specified entity by its natural id.<T> NaturalIdLoadAccess<T>byNaturalId(String entityName)Create aNaturalIdLoadAccessinstance to retrieve the specified entity by its natural id.<T> SimpleNaturalIdLoadAccess<T>bySimpleNaturalId(Class<T> entityClass)Create aSimpleNaturalIdLoadAccessinstance to retrieve the specified entity by its simple (single attribute)natural id.<T> SimpleNaturalIdLoadAccess<T>bySimpleNaturalId(String entityName)Create aSimpleNaturalIdLoadAccessinstance to retrieve the specified entity by itsnatural id.voidcancelQuery()Cancel the execution of the current query.voidclear()Completely clear the session.booleancontains(String entityName, Object object)Determine if the given entity is associated with this session.<T> RootGraph<T>createEntityGraph(Class<T> rootType)RootGraph<?>createEntityGraph(String graphName)QuerycreateNamedQuery(String name)Deprecated.<R> Query<R>createNamedQuery(String name, Class<R> resultClass)Create a typedQueryinstance for the given named query.QuerycreateQuery(CriteriaDelete deleteQuery)Deprecated.<R> Query<R>createQuery(CriteriaQuery<R> criteriaQuery)Create aQueryfor the given JPACriteriaQueryQuerycreateQuery(CriteriaUpdate updateQuery)Deprecated.QuerycreateQuery(String queryString)Deprecated.<R> Query<R>createQuery(String queryString, Class<R> resultClass)Create a typedQueryinstance for the given HQL query string.voiddelete(Object object)Deprecated.useremove(Object)voiddelete(String entityName, Object object)Deprecated.useremove(Object)voiddetach(Object object)Remove this instance from the session cache.voiddisableFetchProfile(String name)Disable a particular fetch profile on this session.voiddisableFilter(String filterName)Disable the named filter for the current session.voidenableFetchProfile(String name)Enable a particular fetch profile on this session.FilterenableFilter(String filterName)Enable the named filter for this current session.voidevict(Object object)Remove this instance from the session cache.voidflush()Force this session to flush.<T> Tget(Class<T> entityType, Object id)Return 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, LockMode lockMode)Return 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.Objectget(String entityName, Object id)Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance.Objectget(String entityName, Object id, LockMode lockMode)Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.Objectget(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.CacheModegetCacheMode()Get the currentcache modefor this session.LockModegetCurrentLockMode(Object object)Determine the currentLockModeof the given managed instance associated with this session.FiltergetEnabledFilter(String filterName)Retrieve a currently enabled filter by name.RootGraph<?>getEntityGraph(String graphName)<T> List<EntityGraph<? super T>>getEntityGraphs(Class<T> entityClass)StringgetEntityName(Object object)Return the entity name for a persistent entity.FlushModeTypegetFlushMode()Get the currentJPA flush modefor this session.FlushModegetHibernateFlushMode()Get the currentflush modefor this session.ObjectgetIdentifier(Object object)Return the identifier value of the given entity associated with this session.LobHelpergetLobHelper()Retrieve this session's helper/delegate for creating LOB instances.<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.ObjectgetReference(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.SessionFactorygetSessionFactory()Get the session factory which created this session.SessionStatisticsgetStatistics()Get the statistics for this session.booleanisDefaultReadOnly()Will 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 a particular fetch profile enabled on this session?booleanisReadOnly(Object entityOrProxy)Is the specified entity or proxy read-only?<T> Tload(Class<T> theClass, Object id)Deprecated.<T> Tload(Class<T> theClass, Object id, LockMode lockMode)Deprecated.<T> Tload(Class<T> theClass, Object id, LockOptions lockOptions)Deprecated.voidload(Object object, Object id)Read the persistent state associated with the given identifier into the given transient instance.Objectload(String entityName, Object id)Deprecated.Objectload(String entityName, Object id, LockMode lockMode)Deprecated.Objectload(String entityName, Object id, LockOptions lockOptions)Deprecated.voidlock(Object object, LockMode lockMode)Obtain the specified lock level on the given managed instance association with this session.voidlock(String entityName, Object object, LockMode lockMode)Obtain the specified lock level on the given managed instance association with this session.<T> Tmerge(String entityName, T object)Copy 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.voidpersist(Object object)Make a transient instance persistent and mark it for later insertion in the database.voidpersist(String entityName, Object object)Make a transient instance persistent and mark it for later insertion in the database.voidrefresh(Object object)Reread the state of the given managed instance associated with this session from the underlying database.voidrefresh(Object object, LockMode lockMode)Reread 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.voidrefresh(String entityName, Object object)Deprecated.userefresh(Object)voidrefresh(String entityName, Object object, LockOptions lockOptions)Deprecated.voidremove(Object object)Mark 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 replacementObjectsave(Object object)Deprecated.usepersist(Object)Objectsave(String entityName, Object object)Deprecated.voidsaveOrUpdate(Object object)Deprecated.voidsaveOrUpdate(String entityName, Object object)Deprecated.SharedSessionBuildersessionWithOptions()Obtain aSessionbuilder with the ability to copy certain information from this session.voidsetCacheMode(CacheMode cacheMode)Set the currentcache modefor this session.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.voidsetFlushMode(FlushModeType flushMode)Set the currentJPA flush modefor this session.voidsetFlushMode(FlushMode flushMode)Deprecated.voidsetHibernateFlushMode(FlushMode flushMode)Set the currentflush modefor this session.voidsetReadOnly(Object entityOrProxy, boolean readOnly)Set an unmodified persistent object to read-only mode, or a read-only object to modifiable mode.voidupdate(Object object)Deprecated.usemerge(Object)voidupdate(String entityName, Object object)Deprecated.-
Methods inherited from interface jakarta.persistence.EntityManager
close, contains, createNamedStoredProcedureQuery, createNativeQuery, createNativeQuery, createNativeQuery, createStoredProcedureQuery, createStoredProcedureQuery, createStoredProcedureQuery, find, find, find, find, getCriteriaBuilder, getDelegate, getEntityManagerFactory, getLockMode, getMetamodel, getProperties, getTransaction, isJoinedToTransaction, isOpen, joinTransaction, lock, lock, refresh, refresh, refresh, setProperty, unwrap
-
Methods inherited from interface org.hibernate.query.QueryProducer
createMutationQuery, createMutationQuery, createMutationQuery, createNamedMutationQuery, createNamedSelectionQuery, createNamedSelectionQuery, createNativeMutationQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createSelectionQuery, createSelectionQuery, createSelectionQuery, getNamedNativeQuery, getNamedNativeQuery, getNamedQuery
-
Methods inherited from interface org.hibernate.SharedSessionContract
beginTransaction, close, createNamedStoredProcedureQuery, createStoredProcedureCall, createStoredProcedureCall, createStoredProcedureCall, createStoredProcedureQuery, createStoredProcedureQuery, createStoredProcedureQuery, doReturningWork, doWork, getCriteriaBuilder, getJdbcBatchSize, getNamedProcedureCall, getTenantIdentifier, getTransaction, isConnected, isOpen, setJdbcBatchSize
-
-
-
-
Method Detail
-
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 currentflush 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
@Deprecated(since="5.2") void setFlushMode(FlushMode flushMode)
Deprecated.Set the currentflush 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.
The
default flush modeis sometimes unnecessarily aggressive. For a logically "read only" session, it's reasonable to set the session's flush mode toFlushMode.MANUALat the start of the session in order to avoid some unnecessary work.- Parameters:
flushMode- the newFlushMode
-
setFlushMode
void setFlushMode(FlushModeType flushMode)
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:
for additional options
-
setHibernateFlushMode
void setHibernateFlushMode(FlushMode flushMode)
Set the currentflush 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.
The
default flush modeis sometimes unnecessarily aggressive. For a logically "read only" session, it's reasonable to set the session's flush mode toFlushMode.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 currentJPA flush modefor this session.- Specified by:
getFlushModein interfaceEntityManager- Returns:
- the
FlushModeTypecurrently in effect
-
getHibernateFlushMode
FlushMode getHibernateFlushMode()
Get the currentflush modefor this session.- Returns:
- the
FlushModecurrently in effect
-
setCacheMode
void setCacheMode(CacheMode cacheMode)
Set the currentcache modefor 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 currentcache modefor this session.- Returns:
- the current cache mode
-
getSessionFactory
SessionFactory getSessionFactory()
Get the session factory which created this session.- Returns:
- the session factory
- See Also:
SessionFactory
-
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:
isReadOnly(Object)
-
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:
setReadOnly(Object,boolean),Query.setReadOnly(boolean)
-
getIdentifier
Object getIdentifier(Object object)
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
boolean contains(String entityName, Object object)
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
void detach(Object object)
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
void evict(Object object)
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(since="6.0") <T> T load(Class<T> theClass, Object id, LockMode lockMode)
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 ofload(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(Class, Object, LockOptions)
-
load
@Deprecated(since="6.0") <T> T load(Class<T> theClass, Object id, LockOptions lockOptions)
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(since="6.0") Object load(String entityName, Object id, LockMode lockMode)
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 ofload(String, Object, LockOptions).- Parameters:
entityName- 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(String, Object, LockOptions)
-
load
@Deprecated(since="6.0") Object load(String entityName, Object id, LockOptions lockOptions)
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- 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(since="6.0") <T> T load(Class<T> theClass, Object id)
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(since="6.0") Object load(String entityName, Object id)
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- a persistent classid- a valid identifier of an existing persistent instance of the class- Returns:
- the persistent instance or proxy
-
load
void load(Object object, Object id)
Read the persistent state associated with the given identifier into the given transient instance.
-
replicate
@Deprecated(since="6.0") void replicate(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:
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
-
save
@Deprecated(since="6.0") Object save(Object object)
Deprecated.usepersist(Object)Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if theassignedgenerator is used.) This operation cascades to associated instances if the association is mapped withCascadeType.SAVE_UPDATE.This operation is very similar to
persist(Object).- Parameters:
object- a transient instance of a persistent class- Returns:
- the generated identifier
-
save
@Deprecated(since="6.0") Object save(String entityName, Object object)
Deprecated.Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if theassignedgenerator is used.) This operation cascades to associated instances if the association is mapped withCascadeType.SAVE_UPDATE.- Parameters:
entityName- the entity nameobject- a transient instance of a persistent class- Returns:
- the generated identifier
-
saveOrUpdate
@Deprecated(since="6.0") void saveOrUpdate(Object object)
Deprecated.Eithersave(Object)orupdate(Object)the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking). This operation cascades to associated instances if the association is mapped withCascadeType.SAVE_UPDATE.- Parameters:
object- a transient or detached instance containing new or updated state- See Also:
save(Object),update(Object object)
-
saveOrUpdate
@Deprecated(since="6.0") void saveOrUpdate(String entityName, Object object)
Deprecated.Eithersave(String, Object)orupdate(String, Object)the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking). This operation cascades to associated instances if the association is mapped withCascadeType.SAVE_UPDATE.- Parameters:
entityName- the entity nameobject- a transient or detached instance containing new or updated state- See Also:
save(String,Object),update(String,Object)
-
update
@Deprecated(since="6.0") void update(Object object)
Deprecated.usemerge(Object)Update the persistent instance with the identifier of the given detached instance. If there is a persistent instance with the same identifier, an exception is thrown. This operation cascades to associated instances if the association is mapped withCascadeType.SAVE_UPDATE.- Parameters:
object- a detached instance containing updated state
-
update
@Deprecated(since="6.0") void update(String entityName, Object object)
Deprecated.Update the persistent instance with the identifier of the given detached instance. If there is a persistent instance with the same identifier, an exception is thrown. This operation cascades to associated instances if the association is mapped withCascadeType.SAVE_UPDATE.- Parameters:
entityName- the entity nameobject- a detached instance containing updated state
-
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
<T> T merge(String entityName, 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.- Parameters:
entityName- the entity nameobject- a detached instance with state to be copied- Returns:
- an updated persistent instance
-
persist
void persist(Object object)
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.- Specified by:
persistin interfaceEntityManager- Parameters:
object- a transient instance to be made persistent
-
persist
void persist(String entityName, Object object)
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
-
delete
@Deprecated(since="6.0") void delete(Object object)
Deprecated.useremove(Object)Remove a persistent instance from the datastore. The argument may be an instance associated with the receivingSessionor a transient instance with an identifier associated with existing persistent state. This operation cascades to associated instances if the association is mapped withCascadeType.REMOVE.- Parameters:
object- the instance to be removed
-
delete
@Deprecated(since="6.0") void delete(String entityName, Object object)
Deprecated.useremove(Object)Remove a persistent instance from the datastore. The second argument may be an instance associated with the receivingSessionor a transient instance with an identifier associated with existing persistent state. This operation cascades to associated instances if the association is mapped withCascadeType.REMOVE.- Parameters:
entityName- the entity name for the instance to be removed.object- the instance to be removed
-
lock
void lock(Object object, LockMode lockMode)
Obtain the specified lock level on the given managed instance association 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).
CascadeType.LOCK.Convenient form of
Session.LockRequest.lock(Object)viabuildLockRequest(LockOptions)- Parameters:
object- a persistent or transient instancelockMode- the lock level- See Also:
buildLockRequest(LockOptions),Session.LockRequest.lock(Object)
- perform a version check with
-
lock
void lock(String entityName, Object object, LockMode lockMode)
Obtain the specified lock level on the given managed instance association 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).
CascadeType.LOCK.Convenient form of
Session.LockRequest.lock(String, Object)viabuildLockRequest(LockOptions)- Parameters:
entityName- the name of the entityobject- a persistent or transient instancelockMode- the lock level- See Also:
buildLockRequest(LockOptions),Session.LockRequest.lock(String, Object)
- perform a version check with
-
buildLockRequest
Session.LockRequest buildLockRequest(LockOptions lockOptions)
Build a newlock requestthat specifies: Timeout and scope are ignored if the specifiedLockModerepresents a form of optimistic locking.Call
Session.LockRequest.lock(Object)to actually obtain the requested lock on a managed entity instance.Example usage:
session.buildLockRequest().setLockMode(LockMode.PESSIMISTIC_WRITE).setTimeOut(60000).lock(entity);- Parameters:
lockOptions- contains the lock level- Returns:
- a
Session.LockRequestthat can be used to lock any given object.
-
refresh
void refresh(Object object)
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
- after inserting a
BloborClob
CascadeType.REFRESH.- Specified by:
refreshin interfaceEntityManager- Parameters:
object- a persistent or detached instance
-
refresh
@Deprecated(since="6.0") void refresh(String entityName, Object object)
Deprecated.userefresh(Object)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
- after inserting a
BloborClob
CascadeType.REFRESH.- Parameters:
entityName- a persistent classobject- a persistent or detached instance
-
refresh
void refresh(Object object, LockMode lockMode)
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 or detached instancelockMode- the lock mode to use- See Also:
refresh(Object, LockOptions)
-
refresh
void refresh(Object object, LockOptions lockOptions)
Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode.- Parameters:
object- a persistent or detached instancelockOptions- contains the lock mode to use
-
refresh
@Deprecated(since="6.0") void refresh(String entityName, Object object, LockOptions lockOptions)
Deprecated.Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode.- Parameters:
entityName- a persistent classobject- a persistent or detached instancelockOptions- contains the lock mode to use
-
remove
void remove(Object object)
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
LockMode getCurrentLockMode(Object object)
Determine the currentLockModeof the given managed instance associated with this session.- Parameters:
object- a persistent instance- 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
<T> T get(Class<T> entityType, Object id)
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).- Parameters:
entityType- the entity typeid- an identifier- Returns:
- a persistent instance or null
-
get
<T> T get(Class<T> entityType, Object id, LockMode lockMode)
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(Class, Object, LockOptions)
-
get
<T> T get(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. 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
Object get(String entityName, Object id)
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
Object get(String entityName, Object id, LockMode lockMode)
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 ofget(String, Object, LockOptions)- Parameters:
entityName- the entity nameid- an identifierlockMode- the lock mode- Returns:
- a persistent instance or null
- See Also:
get(String, Object, LockOptions)
-
get
Object 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. 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
String getEntityName(Object object)
Return the entity name for a persistent entity.- Parameters:
object- a persistent entity associated with this session- Returns:
- the entity name
-
getReference
<T> T getReference(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. 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.- 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
Object 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. 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.- Parameters:
object- a detached persistent instance- Returns:
- the persistent instance or proxy
-
byId
<T> IdentifierLoadAccess<T> byId(String entityName)
Create anIdentifierLoadAccessinstance to retrieve the specified entity type by primary key.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- load delegate for loading the specified entity type by primary key
- Throws:
HibernateException- If the specified entity name cannot be resolved as an entity name
-
byMultipleIds
<T> MultiIdentifierLoadAccess<T> byMultipleIds(Class<T> entityClass)
Create aMultiIdentifierLoadAccessinstance to retrieve multiple entities at once as specified by primary key values.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- load delegate for loading the specified entity type by primary key values
- Throws:
HibernateException- If the specified Class cannot be resolved as a mapped entity
-
byMultipleIds
<T> MultiIdentifierLoadAccess<T> byMultipleIds(String entityName)
Create aMultiIdentifierLoadAccessinstance to retrieve multiple entities at once as specified by primary key values.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- load delegate for loading the specified entity type by primary key values
- Throws:
HibernateException- If the specified entity name cannot be resolved as an entity name
-
byId
<T> IdentifierLoadAccess<T> byId(Class<T> entityClass)
Create anIdentifierLoadAccessinstance to retrieve the specified entity by primary key.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- load delegate for loading the specified entity type by primary key
- Throws:
HibernateException- If the specified Class cannot be resolved as a mapped entity
-
byNaturalId
<T> NaturalIdLoadAccess<T> byNaturalId(String entityName)
Create aNaturalIdLoadAccessinstance to retrieve the specified entity by its natural id.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- load delegate for loading the specified entity type by natural id
- Throws:
HibernateException- If the specified entity name cannot be resolved as an entity name
-
byNaturalId
<T> NaturalIdLoadAccess<T> byNaturalId(Class<T> entityClass)
Create aNaturalIdLoadAccessinstance to retrieve the specified entity by its natural id.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- load delegate for loading the specified entity type by natural id
- Throws:
HibernateException- If the specified Class cannot be resolved as a mapped entity
-
bySimpleNaturalId
<T> SimpleNaturalIdLoadAccess<T> bySimpleNaturalId(String entityName)
Create aSimpleNaturalIdLoadAccessinstance to retrieve the specified entity by itsnatural id.- Parameters:
entityName- the entity name of the entity type to be retrieved- Returns:
- load delegate for loading the specified entity type by natural id
- Throws:
HibernateException- If the specified entityClass cannot be resolved as a mapped entity or if the entity does not define a natural id
-
bySimpleNaturalId
<T> SimpleNaturalIdLoadAccess<T> bySimpleNaturalId(Class<T> entityClass)
Create aSimpleNaturalIdLoadAccessinstance to retrieve the specified entity by its simple (single attribute)natural id.- Parameters:
entityClass- the entity type to be retrieved- Returns:
- load delegate for loading the specified entity type by natural id
- Throws:
HibernateException- If the specified entityClass cannot be resolved as a mapped entity or if the entity does not define a natural id
-
byMultipleNaturalId
<T> NaturalIdMultiLoadAccess<T> byMultipleNaturalId(Class<T> entityClass)
Access to load multiple entities bynatural id.
-
byMultipleNaturalId
<T> NaturalIdMultiLoadAccess<T> byMultipleNaturalId(String entityName)
Access to load multiple entities bynatural id.
-
enableFilter
Filter enableFilter(String filterName)
Enable the named filter for this current session.- Parameters:
filterName- the name of the filter to be enabled.- Returns:
- the
Filterinstance representing the enabled filter.
-
getEnabledFilter
Filter getEnabledFilter(String filterName)
Retrieve a currently enabled filter by name.- Parameters:
filterName- the name of the filter to be retrieved.- Returns:
- the
Filterinstance representing the enabled filter.
-
disableFilter
void disableFilter(String filterName)
Disable the named filter for the current session.- 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
boolean isReadOnly(Object entityOrProxy)
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:
isDefaultReadOnly()
-
setReadOnly
void setReadOnly(Object entityOrProxy, boolean readOnly)
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:
setDefaultReadOnly(boolean),Query.setReadOnly(boolean)
-
isFetchProfileEnabled
boolean isFetchProfileEnabled(String name) throws UnknownProfileException
Is a particular fetch profile enabled on this session?- Parameters:
name- the name of the profile to be checked.- Returns:
- True if fetch profile is enabled; false if not.
- Throws:
UnknownProfileException- Indicates that the given name does not match any known profile names- See Also:
for discussion of this feature
-
enableFetchProfile
void enableFetchProfile(String name) throws UnknownProfileException
Enable a particular fetch profile on this session. If the requested 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 profile names- See Also:
for discussion of this feature
-
disableFetchProfile
void disableFetchProfile(String name) throws UnknownProfileException
Disable a particular fetch profile on this session. If the requested profile is already 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 profile names- See Also:
for discussion of this feature
-
getLobHelper
LobHelper getLobHelper()
Retrieve this session's helper/delegate for creating LOB instances.- Returns:
- this session's
LOB helper
-
sessionWithOptions
SharedSessionBuilder sessionWithOptions()
Obtain aSessionbuilder with the ability to copy certain information from this session.- Returns:
- the session builder
-
addEventListeners
void addEventListeners(SessionEventListener... listeners)
Add one or more listeners to the Session- Parameters:
listeners- the listener(s) to add
-
createEntityGraph
<T> RootGraph<T> createEntityGraph(Class<T> rootType)
- Specified by:
createEntityGraphin interfaceEntityManager
-
createEntityGraph
RootGraph<?> createEntityGraph(String graphName)
- Specified by:
createEntityGraphin interfaceEntityManager
-
getEntityGraph
RootGraph<?> getEntityGraph(String graphName)
- Specified by:
getEntityGraphin interfaceEntityManager
-
getEntityGraphs
<T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass)
- Specified by:
getEntityGraphsin interfaceEntityManager
-
createQuery
<R> Query<R> createQuery(String queryString, Class<R> resultClass)
Description copied from interface:QueryProducerCreate a typedQueryinstance for the given HQL query string.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 Query instance for manipulation and execution
- See Also:
EntityManager.createQuery(String,Class)
-
createQuery
@Deprecated Query createQuery(String queryString)
Deprecated.Description copied from interface:QueryProducerCreate aQueryinstance for the given HQL query, or HQL insert, update, or delete statement.- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer- Parameters:
queryString- The HQL query- Returns:
- The
Queryinstance for manipulation and execution - See Also:
EntityManager.createQuery(String)
-
createNamedQuery
<R> Query<R> createNamedQuery(String name, Class<R> resultClass)
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:
EntityManager.createNamedQuery(String,Class)
-
createNamedQuery
@Deprecated Query createNamedQuery(String name)
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 pre-defined, named query- Returns:
- The
Queryinstance for manipulation and execution - See Also:
EntityManager.createNamedQuery(String)
-
createQuery
<R> Query<R> createQuery(CriteriaQuery<R> criteriaQuery)
Description copied from interface:QueryProducerCreate aQueryfor the given JPACriteriaQuery- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer
-
createQuery
@Deprecated Query createQuery(CriteriaDelete deleteQuery)
Deprecated.Description copied from interface:QueryProducerCreate aMutationQueryfor the given JPACriteriaDelete- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer
-
createQuery
@Deprecated Query createQuery(CriteriaUpdate updateQuery)
Deprecated.Description copied from interface:QueryProducerCreate aMutationQueryfor the given JPACriteriaUpdate- Specified by:
createQueryin interfaceEntityManager- Specified by:
createQueryin interfaceQueryProducer
-
-