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:
Session,
Session, or
Session.
At any given time, an instance may be associated with at most one open session.
Any instance returned by 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 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().
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.
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:
Session throws an exception, the current transaction must be rolled
back and the session must be discarded. The internal state of the Session
cannot be expected to be consistent with the database after the exception occurs.
Session is never thread-safe. It contains various different sorts of
fragile mutable state. Each thread or transaction must obtain its own dedicated
instance from the SessionFactory.
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.
SessionFactory
| Modifier and Type | Class and Description |
|---|---|
| public static interface | Session.LockRequest
Deprecated
since 6.2. simply construct a A set of locking options attached
to the session.
LockOptions and pass
it to lock(Object, LockOptions).
|
| Modifier and Type | Method and Description |
|---|---|
| public void | addEventListeners(SessionEventListener...
the listener(s) to add listeners)Add one or more listeners to the Session |
| public Session. | Returns: aLockRequest that can be used to lock any given object.contains the lock level lockOptions)
Deprecated
since 6.2. use
Build a new lock(Object, LockOptions)
lock request that specifies:
|
| public <T> IdentifierLoadAccess | Returns: an instance ofIdentifierLoadAccess for executing the lookupthe entity type to be retrieved entityClass)Create an |
| public <T> IdentifierLoadAccess | Returns: an instance ofIdentifierLoadAccess for executing the lookupthe entity name of the entity type to be retrieved entityName)Create an |
| public <T> MultiIdentifierLoadAccess | Returns: an instance ofMultiIdentifierLoadAccess for executing the lookupthe entity type to be retrieved entityClass)Create a |
| public <T> MultiIdentifierLoadAccess | Returns: an instance ofMultiIdentifierLoadAccess for executing the lookupthe entity name of the entity type to be retrieved entityName)Create a |
| public <T> NaturalIdMultiLoadAccess | Returns: an instance ofNaturalIdMultiLoadAccess for executing the lookupthe entity type to be retrieved entityClass)Create a |
| public <T> NaturalIdMultiLoadAccess | Returns: an instance ofNaturalIdMultiLoadAccess for executing the lookupthe entity name of the entity type to be retrieved entityName)Create a |
| public <T> NaturalIdLoadAccess | Returns: an instance ofNaturalIdLoadAccess for executing the lookupthe entity type to be retrieved entityClass)Create a |
| public <T> NaturalIdLoadAccess | Returns: an instance ofNaturalIdLoadAccess for executing the lookupthe entity name of the entity type to be retrieved entityName)Create a |
| public <T> SimpleNaturalIdLoadAccess | Returns: an instance ofSimpleNaturalIdLoadAccess for executing the lookupthe entity type to be retrieved entityClass)Create a |
| public <T> SimpleNaturalIdLoadAccess | Returns: an instance ofSimpleNaturalIdLoadAccess for executing the lookupthe entity name of the entity type to be retrieved entityName)Create a |
| public void | |
| public void | |
| public boolean | |
| public <T> RootGraph | createEntityGraph(Class<T>
the root entity class of the graph rootType)Redeclares org. EntityGraph with only a root node.
|
| public RootGraph | createEntityGraph(String
the name of the graph graphName)Redeclares org. EntityGraph,
or return null if there is no graph with the given
name.
|
| public <R> Query | createNamedQuery(String
the name of a query defined in metadata name, Class<R> the type of the query result resultClass)Redeclares org. TypedQuery for executing a
Jakarta Persistence query language named query.
|
| public Query | createNamedQuery(String
the name of a query defined in metadata name)Redeclares org.
Deprecated
Create an instance of Query for executing a named query
(in the Jakarta Persistence query language or in native SQL).
|
| public <R> Query | createQuery(String
a Jakarta Persistence query string queryString, Class<R> the type of the query result resultClass)Redeclares org. TypedQuery for executing a
Jakarta Persistence query language statement.
|
| public Query | createQuery(String
a Jakarta Persistence query string queryString)Redeclares org.
Deprecated
Create an instance of Query for executing a
Jakarta Persistence query language statement.
|
| public <R> Query | createQuery(CriteriaQuery<R>
a criteria query object criteriaQuery)Redeclares org. TypedQuery for executing a
criteria query.
|
| public Query | createQuery(CriteriaDelete<T>
a criteria delete query object deleteQuery)Redeclares org.
Deprecated
since 6.0. use
Create a createMutationQuery(CriteriaDelete)
Query for the given JPA CriteriaDelete.
|
| public Query | createQuery(CriteriaUpdate<T>
a criteria update query object updateQuery)Redeclares org.
Deprecated
since 6.0. use
Create a createMutationQuery(CriteriaUpdate)
Query for the given JPA CriteriaUpdate.
|
| public void | delete(Object
the instance to be removed object)
Deprecated
since 6.0. use
Remove a persistent instance from the datastore.
remove(Object)
|
| public void | delete(String
the entity name for the instance to be removed. entityName, Object the instance to be removed object)
Deprecated
since 6.0. use
Remove a persistent instance from the datastore.
remove(Object)
|
| public void | detach(Object
the managed instance to detach object)Redeclares jakarta. |
| public void | disableFetchProfile(String
the name of the fetch profile to be disabled name)Disable the |
| public void | disableFilter(String
the name of the filter to be disabled. filterName)Disable the named filter for the current session. |
| public void | enableFetchProfile(String
the name of the fetch profile to be enabled name)Enable the |
| public Filter | Returns: theFilter instance representing the enabled filter.the name of the filter to be enabled. filterName)Enable the named filter for this current session. |
| public void | |
| public void | |
| public <T> T | |
| public <T> T | |
| public <T> T | Returns: a persistent instance or nullthe entity type entityType, Object an identifier id, LockOptions the lock mode lockOptions)Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. |
| public Object | |
| public Object | |
| public Object | Returns: a persistent instance or nullthe entity name entityName, Object an identifier id, LockOptions contains the lock mode lockOptions)Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. |
| public CacheMode | |
| public CacheRetrieveMode | |
| public CacheStoreMode | |
| public LockMode | Returns: the current lock modea persistent instance object)Determine the current |
| public Filter | Returns: theFilter instance representing the enabled filter.the name of the filter to be retrieved. filterName)Retrieve a currently enabled filter by name. |
| public RootGraph | getEntityGraph(String
the name of the graph graphName)Redeclares org. EntityGraph as an immutable graph,
or return null if there is no graph with the given
name.
|
| public <T> List | getEntityGraphs(Class<T>
entity class entityClass)Redeclares org. EntityGraphs with the given type.
|
| public String | Returns: the entity namea persistent entity associated with this session object)Return the entity name for a persistent entity. |
| public int | getFetchBatchSize()
Get the maximum batch size for batch fetching associations by id in this session. |
| public FlushModeType | Returns: theFlushModeType currently in effectRedeclares jakarta. |
| public FlushMode | Returns: theFlushMode currently in effectGet the current flush mode for this session. |
| public Object | Returns: the identifiera persistent instance associated with this session object)Return the identifier value of the given entity associated with this session. |
| public LobHelper | Returns: an instance ofLobHelperObtain a factory for instances of |
| public <T> T | Returns: the persistent instance or proxythe entity type entityType, Object the identifier of a persistent instance that exists in the database id)Redeclares jakarta. |
| public Object | Returns: the persistent instance or proxythe entity name entityName, Object the identifier of a persistent instance that exists in the database 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. |
| public <T> T | Returns: the persistent instance or proxya detached persistent instance 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. |
| public SessionFactory | |
| public SessionStatistics | Returns: the session statistics being collected for this sessionGet the statistics for this session. |
| public boolean | Returns: true, loaded entities/proxies will be made read-only by default;
false, loaded entities/proxies will be made modifiable by default.Will entities and proxies that are loaded into this session be made read-only by default? |
| public boolean | Returns: true if the session contains pending changes; false otherwise.Does this session contain any changes which must be synchronized with the database? |
| public boolean | Returns: True if fetch profile is enabled; false if not.the name of the profile name)Is the |
| public boolean | Returns: true if the entity or proxy is read-only,
false if the entity or proxy is modifiable.an entity or proxy entityOrProxy)Is the specified entity or proxy read-only? |
| public boolean | Returns: true is subselect fetching is enabledDetermine if subselect fetching is enabled in this session. |
| public <T> T | Returns: the persistent instance or proxya persistent class theClass, Object a valid identifier of an existing persistent instance of the class id, LockMode the lock level lockMode)
Deprecated
since 6.0. use
Return the persistent instance of the given entity class with the given identifier,
obtaining the specified lock mode, assuming the instance exists.
get(Class, Object, LockMode)
|
| public <T> T | Returns: the persistent instance or proxya persistent class theClass, Object a valid identifier of an existing persistent instance of the class id, LockOptions contains the lock level lockOptions)
Deprecated
since 6.0. use
Return the persistent instance of the given entity class with the given identifier,
obtaining the specified lock mode, assuming the instance exists.
get(Class, Object, LockOptions)
|
| public Object | Returns: the persistent instance or proxythe entity name entityName, Object a valid identifier of an existing persistent instance of the class id, LockMode the lock level lockMode)
Deprecated
since 6.0. use
Return the persistent instance of the given entity class with the given identifier,
obtaining the specified lock mode, assuming the instance exists.
get(String, Object, LockMode)
|
| public Object | Returns: the persistent instance or proxythe entity name entityName, Object a valid identifier of an existing persistent instance of the class id, LockOptions contains the lock level lockOptions)
Deprecated
since 6.0. use
Return the persistent instance of the given entity class with the given identifier,
obtaining the specified lock mode, assuming the instance exists.
get(String, Object, LockOptions)
|
| public <T> T | Returns: the persistent instance or proxya persistent class theClass, Object a valid identifier of an existing persistent instance of the class id)
Deprecated
since 6.0. use
Return the persistent instance of the given entity class with the given identifier,
making the assumption that the instance exists in the database.
getReference(Class, Object)
|
| public Object | Returns: the persistent instance or proxythe entity name entityName, Object a valid identifier of an existing persistent instance of the class id)
Deprecated
since 6.0. use
Return the persistent instance of the given entity class with the given identifier,
making the assumption that the instance exists in the database.
getReference(String, Object)
|
| public void | |
| public void | |
| public void | lock(Object
a persistent or transient instance object, LockOptions the lock options lockOptions)Obtain a lock on the given managed instance associated with this session,
using the given |
| public void | lock(String
the name of the entity entityName, Object a persistent or transient instance object, LockMode the lock level lockMode)
Deprecated
since 6.2. use
Obtain the specified lock level on the given managed instance associated
with this session.
lock(Object, LockMode)
|
| public <T> T | Returns: an updated persistent instancea detached instance with state to be copied object)Redeclares jakarta. |
| public <T> T | |
| public void | persist(Object
a transient instance to be made persistent object)Redeclares jakarta. |
| public void | |
| public void | refresh(Object
a persistent or detached instance object)Redeclares jakarta. |
| public void | refresh(String
the name of the entity entityName, Object a persistent or detached instance object)
Deprecated
since 6.0. use
Reread the state of the given managed instance associated with this session
from the underlying database.
refresh(Object)
|
| public void | |
| public void | refresh(Object
a persistent or detached instance object, LockOptions contains the lock mode to use lockOptions)Reread the state of the given managed instance from the underlying database,
obtaining the given |
| public void | refresh(String
the name of the entity entityName, Object a persistent or detached instance object, LockOptions contains the lock mode to use lockOptions)
Deprecated
since 6.0. use
Reread the state of the given managed instance from the underlying database,
obtaining the given refresh(Object, LockOptions)
LockMode.
|
| public void | remove(Object
the managed persistent instance to remove object)Redeclares jakarta. |
| public void | replicate(Object
a detached instance of a persistent class object, ReplicationMode the replication mode to use replicationMode)
Deprecated
since 6.0. With no real replacement
Persist the state of the given detached instance, reusing the current
identifier value.
|
| public void | replicate(String
the entity name entityName, Object a detached instance of a persistent class object, ReplicationMode the replication mode to use replicationMode)
Deprecated
since 6.0. With no real replacement
Persist the state of the given detached instance, reusing the current
identifier value.
|
| public Object | Returns: the generated identifiera transient instance of a persistent class object)
Deprecated
since 6.0. use
Persist the given transient instance, first assigning a generated identifier.
persist(Object)
|
| public Object | Returns: the generated identifierthe entity name entityName, Object a transient instance of a persistent class object)
Deprecated
since 6.0. use
Persist the given transient instance, first assigning a generated identifier.
persist(String, Object)
|
| public void | saveOrUpdate(Object
a transient or detached instance containing new or updated state object)
Deprecated
since 6.0. use
Either merge(String, Object) or persist(Object)
save(Object) or update(Object) the given
instance, depending upon resolution of the unsaved-value checks (see the
manual for discussion of unsaved-value checking).
|
| public void | saveOrUpdate(String
the entity name entityName, Object a transient or detached instance containing new or updated state object)
Deprecated
since 6.0. use
Either merge(String, Object) or persist(String, Object)
save(String, Object) or update(String, Object)
the given instance, depending upon resolution of the unsaved-value checks
(see the manual for discussion of unsaved-value checking).
|
| public SharedSessionBuilder | Returns: the session builderObtain a |
| public void | |
| public void | setCacheRetrieveMode(CacheRetrieveMode
a JPA-defined cacheRetrieveMode)CacheRetrieveModeEnable or disable reads from the second-level cache. |
| public void | setCacheStoreMode(CacheStoreMode
a JPA-defined cacheStoreMode)CacheStoreModeEnable or disable writes to the second-level cache. |
| public void | setDefaultReadOnly(boolean
true, the default for loaded entities/proxies is read-only;
false, the default for loaded entities/proxies is modifiableChange the default for entities and proxies loaded into this session from modifiable to read-only mode, or from modifiable to read-only mode. |
| public void | setFetchBatchSize(int
the maximum batch size for batch fetching batchSize)Set the maximum batch size for batch fetching associations by id in this session. |
| public void | setFlushMode(FlushModeType
the new flushMode)FlushModeTypeRedeclares jakarta. JPA flush mode for this session.
|
| public void | setHibernateFlushMode(FlushMode
the new flushMode)FlushModeSet the current flush mode for this session. |
| public void | setReadOnly(Object
an entity or proxy entityOrProxy, boolean true if the entity or proxy should be made read-only;
false if the entity or proxy should be made modifiableSet an unmodified persistent object to read-only mode, or a read-only object to modifiable mode. |
| public void | setSubselectFetchingEnabled(boolean
true to enable subselect fetchingEnable or disable subselect fetching in this session. |
| public void | update(Object
a detached instance containing updated state object)
Deprecated
since 6.0. use
Update the persistent instance with the identifier of the given detached
instance.
merge(Object)
|
| public void | update(String
the entity name entityName, Object a detached instance containing updated state object)
Deprecated
since 6.0. use
Update the persistent instance with the identifier of the given detached
instance.
merge(String, Object)
|