Top Description Inners Methods
org.hibernate

public Interface Session

extends SharedSessionContract, EntityManager, HibernateEntityManager, AutoCloseable, Closeable
Known Direct Subinterfaces
org.hibernate.engine.spi.SessionImplementor
Known Direct Implementers
org.hibernate.engine.spi.SessionLazyDelegator
Imports
java.io.Closeable, .Serializable, java.sql.Connection, java.util.List, javax.persistence.EntityGraph, .EntityManager, .FlushModeType, javax.persistence.criteria.CriteriaDelete, .CriteriaQuery, .CriteriaUpdate, org.hibernate.graph.RootGraph, org.hibernate.jpa.HibernateEntityManager, org.hibernate.query.NativeQuery, org.hibernate.stat.SessionStatistics

Deprecated

as a consequence of HibernateEntityManager being deprecated. See corresponding docs for further information.

The main runtime interface between a Java application and Hibernate. This is the central API class abstracting the notion of a persistence service.

The lifecycle of a Session is bounded by the beginning and end of a logical transaction. (Long transactions might span several database transactions.)

The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session

Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). Any instance returned by a get() or load() method is persistent. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

save() and persist() result in an SQL INSERT, delete() in an SQL DELETE and update() or merge() in an SQL UPDATE. Changes to persistent instances are detected at flush time and also result in an SQL UPDATE. saveOrUpdate() and replicate() result in either an INSERT or an UPDATE.

It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.

A Session instance is serializable if its persistent classes are serializable.

A typical transaction should use the following idiom:
Session sess = factory.openSession();
Transaction tx;
try {
    tx = sess.beginTransaction();
    //do some work
    ...
    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
}
finally {
    sess.close();
}

If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs.
Authors
Gavin King, Steve Ebersole
See Also
SessionFactory

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static interface
Session.LockRequest

Contains locking details (LockMode, Timeout and Scope).

Method Summary

Modifier and TypeMethod and Description
public void
addEventListeners(SessionEventListener...
The listener(s) to add
listeners
)

Add one or more listeners to the Session

public Session.LockRequest

Returns:

a lockRequest that can be used to lock the passed object.
buildLockRequest
(LockOptions
contains the lock level
lockOptions
)

Build a LockRequest that specifies the LockMode, pessimistic lock timeout and lock scope.

public IdentifierLoadAccess<T>

Returns:

load delegate for loading the specified entity type by primary key
byId
(String
The entity name of the entity type to be retrieved
entityName
)

Create an IdentifierLoadAccess instance to retrieve the specified entity type by primary key.

public <T> IdentifierLoadAccess<T>

Returns:

load delegate for loading the specified entity type by primary key
byId
(Class<T>
The entity type to be retrieved
entityClass
)

Create an IdentifierLoadAccess instance to retrieve the specified entity by primary key.

public <T> MultiIdentifierLoadAccess<T>

Returns:

load delegate for loading the specified entity type by primary key values
byMultipleIds
(Class<T>
The entity type to be retrieved
entityClass
)

Create a MultiIdentifierLoadAccess instance to retrieve multiple entities at once as specified by primary key values.

public MultiIdentifierLoadAccess<T>

Returns:

load delegate for loading the specified entity type by primary key values
byMultipleIds
(String
The entity name of the entity type to be retrieved
entityName
)

Create a MultiIdentifierLoadAccess instance to retrieve multiple entities at once as specified by primary key values.

public NaturalIdLoadAccess<T>

Returns:

load delegate for loading the specified entity type by natural id
byNaturalId
(String
The entity name of the entity type to be retrieved
entityName
)

Create a NaturalIdLoadAccess instance to retrieve the specified entity by its natural id.

public <T> NaturalIdLoadAccess<T>

Returns:

load delegate for loading the specified entity type by natural id
byNaturalId
(Class<T>
The entity type to be retrieved
entityClass
)

Create a NaturalIdLoadAccess instance to retrieve the specified entity by its natural id.

public SimpleNaturalIdLoadAccess<T>

Returns:

load delegate for loading the specified entity type by natural id
bySimpleNaturalId
(String
The entity name of the entity type to be retrieved
entityName
)

Create a SimpleNaturalIdLoadAccess instance to retrieve the specified entity by its natural id.

public <T> SimpleNaturalIdLoadAccess<T>

Returns:

load delegate for loading the specified entity type by natural id
bySimpleNaturalId
(Class<T>
The entity type to be retrieved
entityClass
)

Create a SimpleNaturalIdLoadAccess instance to retrieve the specified entity by its simple (single attribute) natural id.

public void
cancelQuery()

Cancel the execution of the current query.

public void
clear()

Redeclares javax.persistence.EntityManager.clear.

Completely clear the session.
public boolean

Returns:

true if the given instance is associated with this Session
contains
(String
The entity name
entityName
,
Object
an instance of a persistent class
object
)

Check if this entity is associated with this Session.

public <T> RootGraph<T>
createEntityGraph(Class<T>
class of entity graph
rootType
)

Redeclares javax.persistence.EntityManager.createEntityGraph.

Return a mutable EntityGraph that can be used to dynamically create an EntityGraph.
public RootGraph<?>
createEntityGraph(String
name of an entity graph
graphName
)

Redeclares javax.persistence.EntityManager.createEntityGraph.

Return a mutable copy of the named EntityGraph.
public Query<R>

Returns:

The query instance for manipulation and execution
createFilter
(Object
a persistent collection
collection
,
String
a Hibernate query fragment.
queryString
)

Deprecated (since 5.3) with no real replacement.
Create a Query instance for the given collection and filter string.
public <T> Query<T>
createNamedQuery(String
the name of a query defined in metadata
name
,
Class<T>
the type of the query result
resultType
)

Redeclares org.hibernate.query.QueryProducer.createNamedQuery, javax.persistence.EntityManager.createNamedQuery.

Deprecated as a consequence of Query being deprecated.
Create an instance of TypedQuery for executing a Java Persistence query language named query.
public <T> Query<T>
createQuery(String
a Java Persistence query string
queryString
,
Class<T>
the type of the query result
resultType
)

Redeclares org.hibernate.query.QueryProducer.createQuery, javax.persistence.EntityManager.createQuery.

Deprecated as a consequence of Query being deprecated.
Create an instance of TypedQuery for executing a Java Persistence query language statement.
public <T> Query<T>
createQuery(CriteriaQuery<T>
a criteria query object
criteriaQuery
)

Redeclares org.hibernate.query.QueryProducer.createQuery, javax.persistence.EntityManager.createQuery.

Deprecated as a consequence of Query being deprecated.
Create an instance of TypedQuery for executing a criteria query.
public Query<R>
createQuery(CriteriaUpdate<T>
a criteria update query object
updateQuery
)

Redeclares org.hibernate.query.QueryProducer.createQuery, javax.persistence.EntityManager.createQuery.

Deprecated as a consequence of Query being deprecated.
Create an instance of Query for executing a criteria update query.
public Query<R>
createQuery(CriteriaDelete<T>
a criteria delete query object
deleteQuery
)

Redeclares org.hibernate.query.QueryProducer.createQuery, javax.persistence.EntityManager.createQuery.

Deprecated as a consequence of Query being deprecated.
Create an instance of Query for executing a criteria delete query.
public NativeQuery<T>

Returns:

The query instance for manipulation and execution
createSQLQuery
(String
The SQL query
queryString
)

Redeclares as abstract: org.hibernate.query.QueryProducer.createSQLQuery.

Deprecated (since 5.2) use createNativeQuery(String) instead
Create a NativeQuery instance for the given SQL query string.
public void
delete(Object
the instance to be removed
object
)

Remove a persistent instance from the datastore.

public void
delete(String
The entity name for the instance to be removed.
entityName
,
Object
the instance to be removed
object
)

Remove a persistent instance from the datastore.

public void
disableFetchProfile(String
The name of the fetch profile to be disabled.
name
)

Disable a particular fetch profile on this session.

public void
disableFilter(String
The name of the filter to be disabled.
filterName
)

Disable the named filter for the current session.

public Connection

Returns:

the application-supplied connection or null
disconnect
()

Disconnect the session from its underlying JDBC connection.

public void
enableFetchProfile(String
The name of the fetch profile to be enabled.
name
)

Enable a particular fetch profile on this session.

public Filter

Returns:

The Filter instance representing the enabled filter.
enableFilter
(String
The name of the filter to be enabled.
filterName
)

Enable the named filter for this current session.

public void
evict(Object
The entity to evict
object
)

Remove this instance from the session cache.

public void
flush()

Redeclares javax.persistence.EntityManager.flush.

Force this session to flush.
public <T> T

Returns:

a persistent instance or null
get
(Class<T>
The entity type
entityType
,
Serializable
an identifier
id
)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.

public <T> T

Returns:

a persistent instance or null
get
(Class<T>
The entity type
entityType
,
Serializable
an identifier
id
,
LockMode
the lock mode
lockMode
)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.

public <T> T

Returns:

a persistent instance or null
get
(Class<T>
The entity type
entityType
,
Serializable
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

Returns:

a persistent instance or null
get
(String
the entity name
entityName
,
Serializable
an identifier
id
)

Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance.

public Object

Returns:

a persistent instance or null
get
(String
the entity name
entityName
,
Serializable
an identifier
id
,
LockMode
the lock mode
lockMode
)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.

public Object

Returns:

a persistent instance or null
get
(String
the entity name
entityName
,
Serializable
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

Returns:

The current cache mode.
getCacheMode
()

Get the current cache mode.

public LockMode

Returns:

the current lock mode
getCurrentLockMode
(Object
a persistent instance
object
)

Determine the current lock mode of the given object.

public Filter

Returns:

The Filter instance representing the enabled filter.
getEnabledFilter
(String
The name of the filter to be retrieved.
filterName
)

Retrieve a currently enabled filter by name.

public RootGraph<?>
getEntityGraph(String
name of an existing entity graph
graphName
)

Redeclares javax.persistence.EntityManager.getEntityGraph.

Return a named EntityGraph.
public default <T> List<EntityGraph<? super T>>
getEntityGraphs(Class<T>
entity class
entityClass
)

Implements javax.persistence.EntityManager.getEntityGraphs.

Return all named EntityGraphs that have been defined for the provided class type.
public String

Returns:

the entity name
getEntityName
(Object
a persistent entity
object
)

Return the entity name for a persistent entity.

public FlushModeType

Returns:

The FlushModeType in effect for this Session.
getFlushMode
()

Redeclares javax.persistence.EntityManager.getFlushMode.

Get the flush mode that applies to all objects contained in the persistence context.
public FlushMode

Returns:

The flush mode
getHibernateFlushMode
()

Get the current flush mode for this session.

public Serializable

Returns:

the identifier
getIdentifier
(Object
a persistent instance
object
)

Return the identifier value of the given entity as associated with this session.

public LobHelper

Returns:

This session's LOB helper
getLobHelper
()

Retrieve this session's helper/delegate for creating LOB instances.

public default <T> T

Returns:

the persistent instance or proxy
getReference
(T
a 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

Returns:

The session factory.
getSessionFactory
()

Deprecated as a consequence of SessionFactory being deprecated.
Get the session factory which created this session.
public SessionStatistics

Returns:

The session statistics being collected for this session
getStatistics
()

Get the statistics for this session.

public TypeHelper

Returns:

The TypeHelper associated with this session's SessionFactory
getTypeHelper
()

Convenience access to the TypeHelper associated with this session's SessionFactory.

public boolean

Returns:

true, loaded entities/proxies will be made read-only by default; false, loaded entities/proxies will be made modifiable by default.
isDefaultReadOnly
()

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.
isDirty
()

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.
isFetchProfileEnabled
(String
The name of the profile to be checked.
name
)

Is a particular fetch profile enabled on this session?

public boolean

Returns:

true if the entity or proxy is read-only, false if the entity or proxy is modifiable.
isReadOnly
(Object
an entity or HibernateProxy
entityOrProxy
)

Is the specified entity or proxy read-only?

public <T> T

Returns:

the persistent instance or proxy
load
(Class<T>
a persistent class
theClass
,
Serializable
a valid identifier of an existing persistent instance of the class
id
,
LockMode
the lock level
lockMode
)

Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.

public <T> T

Returns:

the persistent instance or proxy
load
(Class<T>
a persistent class
theClass
,
Serializable
a valid identifier of an existing persistent instance of the class
id
,
LockOptions
contains the lock level
lockOptions
)

Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.

public Object

Returns:

the persistent instance or proxy
load
(String
a persistent class
entityName
,
Serializable
a valid identifier of an existing persistent instance of the class
id
,
LockMode
the lock level
lockMode
)

Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.

public Object

Returns:

the persistent instance or proxy
load
(String
a persistent class
entityName
,
Serializable
a valid identifier of an existing persistent instance of the class
id
,
LockOptions
contains the lock level
lockOptions
)

Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.

public <T> T

Returns:

the persistent instance or proxy
load
(Class<T>
a persistent class
theClass
,
Serializable
a valid identifier of an existing persistent instance of the class
id
)

Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.

public Object

Returns:

the persistent instance or proxy
load
(String
a persistent class
entityName
,
Serializable
a valid identifier of an existing persistent instance of the class
id
)

Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.

public void
load(Object
an "empty" instance of the persistent class
object
,
Serializable
a valid identifier of an existing persistent instance of the class
id
)

Read the persistent state associated with the given identifier into the given transient instance.

public void
lock(Object
a persistent or transient instance
object
,
LockMode
the lock level
lockMode
)

Obtain the specified lock level upon the given object.

public void
lock(String
The name of the entity
entityName
,
Object
a persistent or transient instance
object
,
LockMode
the lock level
lockMode
)

Obtain the specified lock level upon the given object.

public Object

Returns:

an updated persistent instance
merge
(Object
a detached instance with state to be copied
object
)

Redeclares javax.persistence.EntityManager.merge.

Copy the state of the given object onto the persistent object with the same identifier.
public Object

Returns:

an updated persistent instance
merge
(String
The entity name
entityName
,
Object
a detached instance with state to be copied
object
)

Copy the state of the given object onto the persistent object with the same identifier.

public void
persist(Object
a transient instance to be made persistent
object
)

Redeclares javax.persistence.EntityManager.persist.

Make a transient instance persistent.
public void
persist(String
The entity name
entityName
,
Object
a transient instance to be made persistent
object
)

Make a transient instance persistent.

public void
reconnect(Connection
a JDBC connection
connection
)

Reconnect to the given JDBC connection.

public void
refresh(Object
a persistent or detached instance
object
)

Redeclares javax.persistence.EntityManager.refresh.

Re-read the state of the given instance from the underlying database.
public void
refresh(String
a persistent class
entityName
,
Object
a persistent or detached instance
object
)

Re-read the state of the given instance from the underlying database.

public void
refresh(Object
a persistent or detached instance
object
,
LockMode
the lock mode to use
lockMode
)

Re-read the state of the given instance from the underlying database, with the given LockMode.

public void
refresh(Object
a persistent or detached instance
object
,
LockOptions
contains the lock mode to use
lockOptions
)

Re-read the state of the given instance from the underlying database, with the given LockMode.

public void
refresh(String
a persistent class
entityName
,
Object
a persistent or detached instance
object
,
LockOptions
contains the lock mode to use
lockOptions
)

Re-read the state of the given instance from the underlying database, with the given LockMode.

public void
replicate(Object
a detached instance of a persistent class
object
,
ReplicationMode
The replication mode to use
replicationMode
)

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
)

Persist the state of the given detached instance, reusing the current identifier value.

public Serializable

Returns:

the generated identifier
save
(Object
a transient instance of a persistent class
object
)

Persist the given transient instance, first assigning a generated identifier.

public Serializable

Returns:

the generated identifier
save
(String
The entity name
entityName
,
Object
a transient instance of a persistent class
object
)

Persist the given transient instance, first assigning a generated identifier.

public void
saveOrUpdate(Object
a transient or detached instance containing new or updated state
object
)

Either 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
)

Either 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<T extends SharedSessionBuilder>

Returns:

The session builder
sessionWithOptions
()

Obtain a Session builder with the ability to grab certain information from this session.

public void
setCacheMode(CacheMode
The new cache mode.
cacheMode
)

Set the cache mode.

public void
setDefaultReadOnly(boolean
true, the default for loaded entities/proxies is read-only; false, the default for loaded entities/proxies is modifiable
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.

public void
setFlushMode(FlushMode
the new flush mode
flushMode
)

Deprecated (since 5.2) use setHibernateFlushMode(FlushMode) instead
Set the flush mode for this session.
public void
setHibernateFlushMode(FlushMode
the new flush mode
flushMode
)

Set the flush mode for this session.

public void
setReadOnly(Object
an entity or HibernateProxy
entityOrProxy
,
boolean
true if the entity or proxy should be made read-only; false if the entity or proxy should be made modifiable
readOnly
)

Set an unmodified persistent object to read-only mode, or a read-only object to modifiable mode.

public void
update(Object
a detached instance containing updated state
object
)

Update the persistent instance with the identifier of the given detached instance.

public void
update(String
The entity name
entityName
,
Object
a detached instance containing updated state
object
)

Update the persistent instance with the identifier of the given detached instance.

Inherited from java.io.Closeable:
close
Inherited from java.lang.AutoCloseable:
close
Inherited from javax.persistence.EntityManager:
closecontainscreateNamedQuerycreateNamedStoredProcedureQuerycreateNativeQuerycreateNativeQuerycreateNativeQuerycreateQuerycreateStoredProcedureQuerycreateStoredProcedureQuerycreateStoredProcedureQuerydetachfindfindfindfindgetCriteriaBuildergetDelegategetEntityManagerFactorygetLockModegetMetamodelgetPropertiesgetReferencegetTransactionisJoinedToTransactionisOpenjoinTransactionlocklockrefreshrefreshrefreshremovesetFlushModesetPropertyunwrap
Inherited from org.hibernate.jpa.HibernateEntityManager:
getSession
Inherited from org.hibernate.SharedSessionContract:
beginTransactionclosecreateCriteriacreateCriteriacreateCriteriacreateCriteriacreateQuerycreateStoredProcedureCallcreateStoredProcedureCallcreateStoredProcedureCalldoReturningWorkdoWorkgetJdbcBatchSizegetNamedProcedureCallgetNamedQuerygetTenantIdentifiergetTransactionisConnectedisOpensetJdbcBatchSize