Package org.hibernate

Interface Session

All Superinterfaces:
AutoCloseable,EntityManager,QueryProducer,Serializable,SharedSessionContract
All Known Subinterfaces:
EventSource,SessionImplementor
All Known Implementing Classes:
AbstractDelegateSessionImplementor,SessionDelegatorBaseImpl,SessionImpl,SessionLazyDelegator,ToOneDelegateSessionImplementor

public interfaceSessionextendsSharedSessionContract,EntityManager
The main runtime interface between a Java application and Hibernate. Represents the notion of apersistence context, a set of managed entity instances associated with a logical transaction.

The lifecycle of aSession 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 theSession is to offer create, read, and delete operations for instances of mapped entity classes. An instance may be in one of three states with respect to a given open session:

  • transient: never persistent, and not associated with theSession,
  • persistent: currently associated with theSession, or
  • detached: previously persistent, but not currently associated with theSession.

Each persistent instance has apersistent identity determined by its type and identifier value. There may be at most one persistent instance with a given persistent identity associated with a given session. A persistent identity is assigned when aninstance is made persistent.

An instance of an entity class may be associated with at most one open session. Distinct sessions represent state with the same persistent identity using distinct persistent instances of the mapped entity class.

Any instance returned byget(Class, Object),find(Class, Object), or by a query is persistent. A persistent instance might hold references to other entity instances, and sometimes these references areproxied by an intermediate object. When an associated entity has not yet been fetched from the database, references to the unfetched entity are represented by uninitialized proxies. The state of an unfetched entity is automatically fetched from the database when a method of its proxy is invoked, if and only if the proxy is associated with an open session. Otherwise,getReference(Object) may be used to trade a proxy belonging to a closed session for a new proxy associated with the current session.

A transient instance may be made persistent by callingpersist(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 calleddirty checking and can be expensive in some circumstances. Dirty checking may be disabled by marking an entity as read-only usingsetReadOnly(Object, boolean) or simply byevicting it from the persistence context. A session may be set to load entities as read-onlyby default, or this may be controlled at thequery level.

The state of a transient or detached instance may be made persistent by copying it to a persistent instance usingmerge(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().

The persistent state of a managed entity may be refreshed from the database, discarding all modifications to the object held in memory, by callingrefresh(Object).

Fromtime to time, aflush operation is triggered, and the session synchronizes state held in memory with persistent state held in the database by executing SQLinsert,update, anddelete statements. Note that SQL statements are often not executed synchronously by the methods of theSession interface. If synchronous execution of SQL is desired, theStatelessSession allows this.

Each managed instance has an associatedLockMode. By default, the session obtains onlyLockMode.READ on an entity instance it reads from the database andLockMode.WRITE on an entity instance it writes to the database. This behavior is appropriate for programs which use optimistic locking.

A persistence context holds hard references to all its entities and prevents them from being garbage collected. Therefore, aSession is 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, aStatelessSession should be used.

A session might be associated with a container-managed JTA transaction, or it might be in control of its ownresource-local database transaction. In the case of a resource-local transaction, the client must demarcate the beginning and end of the transaction using aTransaction. A typical resource-local transaction should use the following idiom:

 Session session = factory.openSession(); Transaction tx = null; try {     tx = session.beginTransaction();     //do some work     ...     tx.commit(); } catch (Exception e) {     if (tx!=null) tx.rollback();     throw e; } finally {     session.close(); }

It's crucially important to appreciate the following restrictions and why they exist:

  • If theSession throws an exception, the current transaction must be rolled back and the session must be discarded. The internal state of theSession cannot be expected to be consistent with the database after the exception occurs.
  • At the end of a logical transaction, the session must be explicitlydestroyed, so that all JDBC resources may be released.
  • ASession is never thread-safe. It contains various different sorts of fragile mutable state. Each thread or transaction must obtain its own dedicated instance from theSessionFactory.

An easy way to be sure that session and transaction management is being done correctly is tolet the factory do it:

 sessionFactory.inTransaction(session -> {     //do the work     ... });

A session may be used toexecute JDBC work using its JDBC connection and transaction:

 session.doWork(connection -> {     try ( PreparedStatement ps = connection.prepareStatement( " ... " ) ) {         ps.execute();     } });

ASession instance is serializable if its entities are serializable.

EverySession is a JPAEntityManager. Furthermore, when Hibernate is acting as the JPA persistence provider, the methodEntityManager.unwrap(Class) may be used to obtain the underlyingSession.

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 fromEntityManager, are overloaded with a form that accepts an explicit entity name along with the instance. An alternative solution to this problem is to provide anEntityNameResolver.

See Also:
  • Method Details

    • flush

      void flush()
      Force this session to flush. Must be called at the end of a unit of work, before the transaction is committed. Depending on the 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:
      flush in interface EntityManager
      Throws:
      HibernateException - if changes could not be synchronized with the database
    • setFlushMode

      void setFlushMode(FlushModeType flushMode)
      Set the currentJPA flush mode for this session.

      Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. The current flush mode determines when the session is automatically flushed.

      Specified by:
      setFlushMode in interface EntityManager
      Parameters:
      flushMode - the newFlushModeType
      See Also:
    • setHibernateFlushMode

      void setHibernateFlushMode(FlushMode flushMode)
      Set the currentflush mode for this session.

      Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. The current flush mode determines when the session is automatically flushed.

      Thedefault flush mode is sometimes unnecessarily aggressive. For a logically "read only" session, it's reasonable to set the session's flush mode toFlushMode.MANUAL at the start of the session in order to avoid some unnecessary work.

      Note thatFlushMode defines more options thanFlushModeType.

      Parameters:
      flushMode - the newFlushMode
    • getFlushMode

      FlushModeType getFlushMode()
      Get the currentJPA flush mode for this session.
      Specified by:
      getFlushMode in interface EntityManager
      Returns:
      theFlushModeType currently in effect
      See Also:
    • getHibernateFlushMode

      FlushMode getHibernateFlushMode()
      Get the currentflush mode for this session.
      Returns:
      theFlushMode currently in effect
    • setCacheMode

      void setCacheMode(CacheMode cacheMode)
      Set the currentcache mode for this session.

      The cache mode determines the manner in which this session can interact with the second level cache.

      Specified by:
      setCacheMode in interface SharedSessionContract
      Parameters:
      cacheMode - the new cache mode
    • getCacheMode

      CacheMode getCacheMode()
      Get the currentcache mode for this session.
      Specified by:
      getCacheMode in interface SharedSessionContract
      Returns:
      the current cache mode
    • getCacheStoreMode

      CacheStoreMode getCacheStoreMode()
      The JPA-definedCacheStoreMode.
      Specified by:
      getCacheStoreMode in interface EntityManager
      Since:
      6.2
      See Also:
    • getCacheRetrieveMode

      CacheRetrieveMode getCacheRetrieveMode()
      The JPA-definedCacheRetrieveMode.
      Specified by:
      getCacheRetrieveMode in interface EntityManager
      Since:
      6.2
      See Also:
    • setCacheStoreMode

      void setCacheStoreMode(CacheStoreMode cacheStoreMode)
      Enable or disable writes to the second-level cache.
      Specified by:
      setCacheStoreMode in interface EntityManager
      Parameters:
      cacheStoreMode - a JPA-definedCacheStoreMode
      Since:
      6.2
      See Also:
    • setCacheRetrieveMode

      void setCacheRetrieveMode(CacheRetrieveMode cacheRetrieveMode)
      Enable or disable reads from the second-level cache.
      Specified by:
      setCacheRetrieveMode in interface EntityManager
      Parameters:
      cacheRetrieveMode - a JPA-definedCacheRetrieveMode
      Since:
      6.2
      See Also:
    • getFetchBatchSize

      int getFetchBatchSize()
      Get the maximum batch size for batch fetching associations by id in this session.
      Since:
      6.3
    • setFetchBatchSize

      void setFetchBatchSize(int batchSize)
      Set the maximum batch size for batch fetching associations by id in this session. Override thefactory-level default controlled by the configuration property"hibernate.default_batch_fetch_size".

      • IfbatchSize>1, then batch fetching is enabled.
      • IfbatchSize<0, the batch size is inherited from the factory-level setting.
      • Otherwise, batch fetching is disabled.
      Parameters:
      batchSize - the maximum batch size for batch fetching
      Since:
      6.3
      See Also:
    • isSubselectFetchingEnabled

      boolean isSubselectFetchingEnabled()
      Determine if subselect fetching is enabled in this session.
      Returns:
      true is subselect fetching is enabled
      Since:
      6.3
    • setSubselectFetchingEnabled

      void setSubselectFetchingEnabled(boolean enabled)
      Enable or disable subselect fetching in this session. Override thefactory-level default controlled by the configuration property"hibernate.use_subselect_fetch".
      Parameters:
      enabled -true to enable subselect fetching
      Since:
      6.3
      See Also:
    • getSessionFactory

      SessionFactory getSessionFactory()
      Get the session factory which created this session.
      Returns:
      the session factory
      See Also:
    • cancelQuery

      void cancelQuery()
      Cancel the execution of the current query.

      This is the sole method on session which may be safely called from another thread.

      Throws:
      HibernateException - if there was a problem cancelling the query
    • isDirty

      boolean isDirty()
      Does this session contain any changes which must be synchronized with the database? In other words, would any DML operations be executed if we flushed this session?
      Returns:
      true if the session contains pending changes;false otherwise.
    • 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 useisReadOnly(Object).

      Returns:
      true, loaded entities/proxies will be made read-only by default;false, loaded entities/proxies will be made modifiable by default.
      See Also:
    • setDefaultReadOnly

      void setDefaultReadOnly(boolean readOnly)
      Change the default for entities and proxies loaded into this session from modifiable to read-only mode, or from modifiable to read-only mode.

      Read-only entities are not dirty-checked and snapshots of persistent state are not maintained. Read-only entities can be modified, but changes are not persisted.

      When a proxy is initialized, the loaded entity will have the same read-only/modifiable setting as the uninitialized proxy has, regardless of the session's current setting.

      To change the read-only/modifiable setting for a particular entity or proxy that already belongs to this session usesetReadOnly(Object, boolean).

      To override this session's read-only/modifiable setting for all entities and proxies loaded by a certainQuery useQuery.setReadOnly(boolean).

      Parameters:
      readOnly -true, the default for loaded entities/proxies is read-only;false, the default for loaded entities/proxies is modifiable
      See Also:
    • getIdentifier

      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 name
      object - an instance of a persistent class
      Returns:
      true if 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:
      detach in interface EntityManager
      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 fordetach(Object).

      Parameters:
      object - the managed entity to evict
      Throws:
      NullPointerException - if the passed object isnull
      IllegalArgumentException - if the passed object is not mapped as an entity
    • find

      <T> T find(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.

      The object returned byget() orfind() is either an unproxied instance of the given entity class, or a fully-fetched proxy object.

      This operation requestsLockMode.NONE, that is, no lock, allowing the object to be retrieved from the cache without the cost of database access. However, if it is necessary to read the state from the database, the object will be returned with the lock modeLockMode.READ.

      To bypass thesecond-level cache, and ensure that the state of the requested instance is read directly from the database, either:

      Specified by:
      find in interface EntityManager
      Parameters:
      entityType - the entity type
      id - an identifier
      Returns:
      a fully-fetched persistent instance or null
      API Note:
      This operation is very similar toget(Class, Object).
    • findMultiple

      <E> List<E> findMultiple(Class<E> entityType,List<?> ids,FindOption... options)
      Return the persistent instances of the given entity class with the given identifiers as a list. The position of an instance in the returned list matches the position of its identifier in the given list of identifiers, and the returned list contains a null value if there is no persistent instance matching a given identifier. If an instance is already associated with the session, that instance is returned. This method never returns an uninitialized instance.

      Every object returned byfindMultiple() is either an unproxied instance of the given entity class, or a fully-fetched proxy object.

      This method acceptsBatchSize as an option, allowing control over the number of records retrieved in a single database request. The performance impact of setting a batch size depends on whether a SQL array may be used to pass the list of identifiers to the database:

      • for databases whichsupport standard SQL arrays, a smaller batch size might be extremely inefficient compared to a very large batch size or no batching at all, but
      • on the other hand, for databases with no SQL array type, a large batch size results in long SQL statements with many JDBC parameters.

      For more advanced cases, usebyMultipleIds(Class), which returns an instance ofMultiIdentifierLoadAccess.

      Parameters:
      entityType - the entity type
      ids - the list of identifiers
      options - options, if any
      Returns:
      an ordered list of persistent instances, with null elements representing missing entities, whose positions in the list match the positions of their ids in the given list of identifiers
      Since:
      7.0
      See Also:
    • findMultiple

      <E> List<E> findMultiple(EntityGraph<E> entityGraph,List<?> ids,FindOption... options)
      Return the persistent instances of the root entity of the givenEntityGraph with the given identifiers as a list, fetching the associations specified by the graph, which is interpreted as aload graph. The position of an instance in the returned list matches the position of its identifier in the given list of identifiers, and the returned list contains a null value if there is no persistent instance matching a given identifier. If an instance is already associated with the session, that instance is returned. This method never returns an uninitialized instance.

      Every object returned byfindMultiple() is either an unproxied instance of the given entity class, or a fully-fetched proxy object.

      This method acceptsBatchSize as an option, allowing control over the number of records retrieved in a single database request. The performance impact of setting a batch size depends on whether a SQL array may be used to pass the list of identifiers to the database:

      • for databases whichsupport standard SQL arrays, a smaller batch size might be extremely inefficient compared to a very large batch size or no batching at all, but
      • on the other hand, for databases with no SQL array type, a large batch size results in long SQL statements with many JDBC parameters.

      For more advanced cases, usebyMultipleIds(Class), which returns an instance ofMultiIdentifierLoadAccess.

      Parameters:
      entityGraph - the entity graph interpreted as a load graph
      ids - the list of identifiers
      options - options, if any
      Returns:
      an ordered list of persistent instances, with null elements representing missing entities, whose positions in the list match the positions of their ids in the given list of identifiers
      Since:
      7.0
      See Also:
    • load

      void load(Object object,Object id)
      Read the persistent state associated with the given identifier into the given transient instance.
      Parameters:
      object - a transient instance of an entity class
      id - an identifier
    • replicate

      @Deprecated(since="6.0")void replicate(Object object,ReplicationMode replicationMode)
      Deprecated.
      With no real replacement. For some use cases tryStatelessSession.upsert(Object).
      Persist the state of the given detached instance, reusing the current identifier value. This operation cascades to associated instances if the association is mapped withCascadeType.REPLICATE.
      Parameters:
      object - a detached instance of a persistent class
      replicationMode - the replication mode to use
    • replicate

      @Deprecated(since="6.0")void replicate(String entityName,Object object,ReplicationMode replicationMode)
      Deprecated.
      With no real replacement. For some use cases tryStatelessSession.upsert(Object).
      Persist the state of the given detached instance, reusing the current identifier value. This operation cascades to associated instances if the association is mapped withCascadeType.REPLICATE.
      Parameters:
      entityName - the entity name
      object - a detached instance of a persistent class
      replicationMode - the replication mode to use
    • merge

      <T> T merge(T object)
      Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped withCascadeType.MERGE.
      Specified by:
      merge in interface EntityManager
      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 name
      object - a detached instance with state to be copied
      Returns:
      an updated persistent instance
    • merge

      <T> T merge(T object,EntityGraph<?> loadGraph)
      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:
      object - a detached instance with state to be copied
      loadGraph - entity graph interpreted as a load graph
      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 an entity with agenerated id,persist() ultimately results in generation of an identifier for the given instance. But this may happen asynchronously, when the session isflushed, depending on the identifier generation strategy.

      Specified by:
      persist in interface EntityManager
      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 agenerated id,persist() ultimately results in generation of an identifier for the given instance. But this may happen asynchronously, when the session isflushed, depending on the identifier generation strategy.

      Parameters:
      entityName - the entity name
      object - a transient instance to be made persistent
    • lock

      void lock(Object object,LockMode lockMode)
      Obtain the specified lock level on the given managed instance associated with this session. This operation may be used to:

      If the requested lock mode is already held on the given entity, this operation has no effect.

      This operation cascades to associated instances if the association is mapped withCascadeType.LOCK.

      The modesLockMode.WRITE andLockMode.UPGRADE_SKIPLOCKED are not legal arguments tolock().

      Parameters:
      object - a persistent instance associated with this session
      lockMode - the lock level
      See Also:
    • lock

      void lock(Object object,LockMode lockMode,LockOption... lockOptions)
      Obtain the specified lock level on the given managed instance associated with this session, applying any other specified options. This operation may be used to:

      If the requested lock mode is already held on the given entity, this operation has no effect.

      This operation cascades to associated instances if the association is mapped withCascadeType.LOCK.

      The modesLockMode.WRITE andLockMode.UPGRADE_SKIPLOCKED are not legal arguments tolock().

      Parameters:
      object - a persistent instance associated with this session
      lockMode - the lock level
      See Also:
    • 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,
      • afterexecuting any HQL update or delete statement,
      • afterexecuting a native SQL statement, or
      • after inserting aBlob orClob.

      This operation cascades to associated instances if the association is mapped withCascadeType.REFRESH.

      This operation requestsLockMode.READ. To obtain a stronger lock, callEntityManager.refresh(Object, RefreshOption...), passing the appropriateLockMode as an option.

      Specified by:
      refresh in interface EntityManager
      Parameters:
      object - a persistent instance associated with this session
    • 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.

      Except when operating in fully JPA-compliant mode, this operation does, contrary to the JPA specification, accept a detached entity instance.

      Specified by:
      remove in interface EntityManager
      Parameters:
      object - the managed persistent instance to remove, or a detached instance unless operating in fully JPA-compliant mode
    • getCurrentLockMode

      LockMode getCurrentLockMode(Object object)
      Determine the currentlock mode held on the given managed instance associated with this session.

      Unlike the JPA-standardEntityManager.getLockMode(java.lang.Object), this operation may be called when no transaction is active, in which case it should returnLockMode.NONE, indicating that no pessimistic lock is held on the given entity.

      Parameters:
      object - a persistent instance associated with this session
      Returns:
      the lock mode currently held on the given entity
      Throws:
      IllegalStateException - if the given instance is not associated with this persistence context
      ObjectDeletedException - if the given instance was alreadyremoved
    • clear

      void clear()
      Completely clear the persistence context. Evict all loaded instances, causing every managed entity currently associated with this session to transition to the detached state, and cancel all pending insertions, updates, and deletions.

      Does not close open iterators or instances ofScrollableResults.

      Specified by:
      clear in interface EntityManager
    • get

      @Deprecated(since="7.0",forRemoval=true)<T> T get(Class<T> entityType,Object id)
      Deprecated, for removal: This API element is subject to removal in a future version.
      Because the semantics of this method may change in a future release. Usefind(Class, Object) instead.
      Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.

      The object returned byget() orfind() is either an unproxied instance of the given entity class, or a fully-fetched proxy object.

      This operation requestsLockMode.NONE, that is, no lock, allowing the object to be retrieved from the cache without the cost of database access. However, if it is necessary to read the state from the database, the object will be returned with the lock modeLockMode.READ.

      To bypass the second-level cache, and ensure that the state is read from the database, either:

      Parameters:
      entityType - the entity type
      id - an identifier
      Returns:
      a persistent instance or null
      API Note:
      This operation is very similar tofind(Class, Object).
    • get

      @Deprecated(since="7.0",forRemoval=true)<T> T get(Class<T> entityType,Object id,LockMode lockMode)
      Deprecated, for removal: This API element is subject to removal in a future version.
      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 type
      id - an identifier
      lockMode - the lock mode
      Returns:
      a persistent instance or null
      API Note:
      This operation is very similar toEntityManager.find(Class, Object, LockModeType).
    • get

      @Deprecated(since="7",forRemoval=true)Object get(String entityName,Object id)
      Deprecated, for removal: This API element is subject to removal in a future version.
      The semantics of this method may change in a future release. UseSessionFactory.createGraphForDynamicEntity(String) together withEntityManager.find(EntityGraph, Object, FindOption...) to loaddynamic entities.
      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 name
      id - an identifier
      Returns:
      a persistent instance or null
      See Also:
    • get

      @Deprecated(since="7.0",forRemoval=true)Object get(String entityName,Object id,LockMode lockMode)
      Deprecated, for removal: This API element is subject to removal in a future version.
      The semantics of this method may change in a future release.
      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 name
      id - an identifier
      lockMode - the lock mode
      Returns:
      a persistent instance or null
      See Also:
    • get

      @Deprecated(since="7.0",forRemoval=true)<T> T get(Class<T> entityType,Object id,LockOptions lockOptions)
      Deprecated, for removal: This API element is subject to removal in a future version.
      This method will be removed. UseEntityManager.find(Class, Object, FindOption...) instead.
      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 type
      id - an identifier
      lockOptions - the lock mode
      Returns:
      a persistent instance or null
    • get

      @Deprecated(since="7.0",forRemoval=true)Object get(String entityName,Object id,LockOptions lockOptions)
      Deprecated, for removal: This API element is subject to removal in a future version.
      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 name
      id - an identifier
      lockOptions - contains the lock mode
      Returns:
      a persistent instance or null
    • lock

      @Deprecated(since="7.0",forRemoval=true)void lock(Object object,LockOptions lockOptions)
      Deprecated, for removal: This API element is subject to removal in a future version.
      This method will be removed. UseEntityManager.lock(Object, LockModeType, LockOption...) instead
      Obtain a lock on the given managed instance associated with this session, using the givenlock options.

      This operation cascades to associated instances if the association is mapped withCascadeType.LOCK.

      Parameters:
      object - a persistent instance associated with this session
      lockOptions - the lock options
      Since:
      6.2
    • refresh

      @Deprecated(since="7.0",forRemoval=true)void refresh(Object object,LockOptions lockOptions)
      Deprecated, for removal: This API element is subject to removal in a future version.
      This method will be removed. UseEntityManager.refresh(Object, RefreshOption...) instead
      Reread the state of the given managed instance from the underlying database, obtaining the givenLockMode.
      Parameters:
      object - a persistent instance associated with this session
      lockOptions - contains the lock mode to use
    • 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 thatHibernate.createDetachedProxy(SessionFactory, Class, Object) may be used to obtain adetached reference.

      It's sometimes necessary to narrow a reference returned bygetReference() to a subtype of the given entity type. A direct Java typecast should never be used in this situation. Instead, the methodHibernate.unproxy(Object, Class) is the recommended way to narrow the type of a proxy object. Alternatively, a new reference may be obtained by simply callinggetReference() again, passing the subtype. Either way, the narrowed reference will usually not be identical to the original reference, when the references are compared using the== operator.

      Specified by:
      getReference in interface EntityManager
      Parameters:
      entityType - the entity type
      id - 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 name
      id - the identifier of a persistent instance that exists in the database
      Returns:
      the persistent instance or proxy
    • getReference

      <T> T getReference(T object)
      Return a reference to the persistent instance with the same identity as the given instance, which might be detached, making the assumption that the instance is still persistent in the database. This method never results in access to the underlying data store, and thus might return a proxy that is initialized on-demand, when a non-identifier method is accessed.
      Specified by:
      getReference in interface EntityManager
      Parameters:
      object - a detached persistent instance
      Returns:
      the persistent instance or proxy
      Since:
      6.0
    • byId

      <T> IdentifierLoadAccess<T> byId(Class<T> entityClass)
      Create anIdentifierLoadAccess instance to retrieve an instance of the given entity type by its primary key.
      Parameters:
      entityClass - the entity type to be retrieved
      Returns:
      an instance ofIdentifierLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given class does not resolve as a mapped entity
    • byId

      <T> IdentifierLoadAccess<T> byId(String entityName)
      Create anIdentifierLoadAccess instance to retrieve an instance of the named entity type by its primary key.
      Parameters:
      entityName - the entity name of the entity type to be retrieved
      Returns:
      an instance ofIdentifierLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given name does not resolve to a mapped entity
    • byMultipleIds

      <T> MultiIdentifierLoadAccess<T> byMultipleIds(Class<T> entityClass)
      Create aMultiIdentifierLoadAccess instance to retrieve multiple instances of the given entity type by their primary key values, using batching.
      Parameters:
      entityClass - the entity type to be retrieved
      Returns:
      an instance ofMultiIdentifierLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given class does not resolve as a mapped entity
      See Also:
    • byMultipleIds

      <T> MultiIdentifierLoadAccess<T> byMultipleIds(String entityName)
      Create aMultiIdentifierLoadAccess instance to retrieve multiple instances of the named entity type by their primary key values, using batching.
      Parameters:
      entityName - the entity name of the entity type to be retrieved
      Returns:
      an instance ofMultiIdentifierLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given name does not resolve to a mapped entity
    • byNaturalId

      <T> NaturalIdLoadAccess<T> byNaturalId(Class<T> entityClass)
      Create aNaturalIdLoadAccess instance to retrieve an instance of the given entity type by itsnatural id, which may be a composite natural id. The entity must have at least one attribute annotatedNaturalId.
      Parameters:
      entityClass - the entity type to be retrieved
      Returns:
      an instance ofNaturalIdLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given class does not resolve as a mapped entity, or if the entity does not declare a natural id
    • byNaturalId

      <T> NaturalIdLoadAccess<T> byNaturalId(String entityName)
      Create aNaturalIdLoadAccess instance to retrieve an instance of the named entity type by itsnatural id, which may be a composite natural id. The entity must have at least one attribute annotatedNaturalId.
      Parameters:
      entityName - the entity name of the entity type to be retrieved
      Returns:
      an instance ofNaturalIdLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given name does not resolve to a mapped entity, or if the entity does not declare a natural id
    • bySimpleNaturalId

      <T> SimpleNaturalIdLoadAccess<T> bySimpleNaturalId(Class<T> entityClass)
      Create aSimpleNaturalIdLoadAccess instance to retrieve an instance of the given entity type by itsnatural id, which must be a simple (non-composite) value. The entity must have exactly one attribute annotatedNaturalId.
      Parameters:
      entityClass - the entity type to be retrieved
      Returns:
      an instance ofSimpleNaturalIdLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given class does not resolve as a mapped entity, or if the entity does not declare a natural id
    • bySimpleNaturalId

      <T> SimpleNaturalIdLoadAccess<T> bySimpleNaturalId(String entityName)
      Create aSimpleNaturalIdLoadAccess instance to retrieve an instance of the named entity type by itsnatural id, which must be a simple (non-composite) value. The entity must have exactly one attribute annotatedNaturalId.
      Parameters:
      entityName - the entity name of the entity type to be retrieved
      Returns:
      an instance ofSimpleNaturalIdLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given name does not resolve to a mapped entity, or if the entity does not declare a natural id
    • byMultipleNaturalId

      <T> NaturalIdMultiLoadAccess<T> byMultipleNaturalId(Class<T> entityClass)
      Create aMultiIdentifierLoadAccess instance to retrieve multiple instances of the given entity type by their bynatural id values, using batching.
      Parameters:
      entityClass - the entity type to be retrieved
      Returns:
      an instance ofNaturalIdMultiLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given class does not resolve as a mapped entity, or if the entity does not declare a natural id
    • byMultipleNaturalId

      <T> NaturalIdMultiLoadAccess<T> byMultipleNaturalId(String entityName)
      Create aMultiIdentifierLoadAccess instance to retrieve multiple instances of the named entity type by their bynatural id values, using batching.
      Parameters:
      entityName - the entity name of the entity type to be retrieved
      Returns:
      an instance ofNaturalIdMultiLoadAccess for executing the lookup
      Throws:
      HibernateException - If the given name does not resolve to a mapped entity, or if the entity does not declare a natural id
    • getStatistics

      SessionStatistics getStatistics()
      Get thestatistics 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 useisDefaultReadOnly()

      Parameters:
      entityOrProxy - an entity or proxy
      Returns:
      true if the entity or proxy is read-only,false if the entity or proxy is modifiable.
      See Also:
    • setReadOnly

      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 usesetDefaultReadOnly(boolean).

      To override this session's read-only/modifiable setting for entities and proxies loaded by aQuery useQuery.setReadOnly(boolean)

      Parameters:
      entityOrProxy - an entity or proxy
      readOnly -true if the entity or proxy should be made read-only;false if the entity or proxy should be made modifiable
      See Also:
    • isFetchProfileEnabled

      boolean isFetchProfileEnabled(String name) throwsUnknownProfileException
      Is thefetch profile with the given name enabled in this session?
      Parameters:
      name - the name of the profile
      Returns:
      True if fetch profile is enabled; false if not.
      Throws:
      UnknownProfileException - Indicates that the given name does not match any known fetch profile names
      See Also:
    • enableFetchProfile

      void enableFetchProfile(String name) throwsUnknownProfileException
      Enable thefetch profile with the given name in this session. If the requested fetch profile is already enabled, the call has no effect.
      Parameters:
      name - the name of the fetch profile to be enabled
      Throws:
      UnknownProfileException - Indicates that the given name does not match any known fetch profile names
      See Also:
    • disableFetchProfile

      void disableFetchProfile(String name) throwsUnknownProfileException
      Disable thefetch profile with the given name in this session. If the requested fetch profile is not currently enabled, the call has no effect.
      Parameters:
      name - the name of the fetch profile to be disabled
      Throws:
      UnknownProfileException - Indicates that the given name does not match any known fetch profile names
      See Also:
    • getLobHelper

      LobHelper getLobHelper()
      Obtain afactory for instances ofBlob andClob.
      Returns:
      an instance ofLobHelper
    • getManagedEntities

      @IncubatingCollection<?> getManagedEntities()
      Obtain the collection of all managed entities which belong to this persistence context.
      Since:
      7.0
    • getManagedEntities

      @IncubatingCollection<?> getManagedEntities(String entityName)
      Obtain a collection of all managed instances of the entity type with the given entity name which belong to this persistence context.
      Since:
      7.0
    • getManagedEntities

      @Incubating<E> Collection<E> getManagedEntities(Class<E> entityType)
      Obtain a collection of all managed entities of the given type which belong to this persistence context. This operation is not polymorphic, and does not return instances of subtypes of the given entity type.
      Since:
      7.0
    • getManagedEntities

      @Incubating<E> Collection<E> getManagedEntities(EntityType<E> entityType)
      Obtain a collection of all managed entities of the given type which belong to this persistence context. This operation is not polymorphic, and does not return instances of subtypes of the given entity type.
      Since:
      7.0
    • sessionWithOptions

      SharedSessionBuilder sessionWithOptions()
      Obtain aSession builder 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
    • setProperty

      void setProperty(String propertyName,Object value)
      Set a hint. The hints understood by Hibernate are enumerated byAvailableHints.
      Specified by:
      setProperty in interface EntityManager
      See Also:
      API Note:
      Hints are aJPA-standard way to control provider-specific behavior of theEntityManager. Clients of the native API defined by Hibernate should make use of type-safe operations of this interface. For example,enableFetchProfile(String) should be used in preference to the hintHibernateHints.HINT_FETCH_PROFILE.
    • createEntityGraph

      <T> RootGraph<T> createEntityGraph(Class<T> rootType)
      Create a new mutable instance ofEntityGraph, with only a root node, allowing programmatic definition of the graph from scratch.
      Specified by:
      createEntityGraph in interface EntityManager
      Specified by:
      createEntityGraph in interface SharedSessionContract
      Parameters:
      rootType - The root entity of the graph
      See Also:
    • createEntityGraph

      RootGraph<?> createEntityGraph(String graphName)
      Create a new mutable instance ofEntityGraph, based on a predefinednamed entity graph, allowing customization of the graph, or returnnull if there is no predefined graph with the given name.
      Specified by:
      createEntityGraph in interface EntityManager
      Specified by:
      createEntityGraph in interface SharedSessionContract
      Parameters:
      graphName - The name of the predefined named entity graph
      See Also:
      API Note:
      This method returnsRootGraph<?>, requiring an unchecked typecast before use. It's cleaner to obtain a graph usingSharedSessionContract.createEntityGraph(Class, String) instead.
    • getEntityGraph

      RootGraph<?> getEntityGraph(String graphName)
      Obtain an immutable reference to a predefinednamed entity graph or returnnull if there is no predefined graph with the given name.
      Specified by:
      getEntityGraph in interface EntityManager
      Specified by:
      getEntityGraph in interface SharedSessionContract
      Parameters:
      graphName - The name of the predefined named entity graph
      See Also:
      API Note:
      This method returnsRootGraph<?>, requiring an unchecked typecast before use. It's cleaner to obtain a graph using the static metamodel for the class which defines the graph, or by callingEntityManagerFactory.getNamedEntityGraphs(Class) instead.
    • getEntityGraphs

      <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass)
      Retrieve all namedEntityGraphs with the given root entity type.
      Specified by:
      getEntityGraphs in interface EntityManager
      Specified by:
      getEntityGraphs in interface SharedSessionContract
      See Also:
    • createQuery

      <R> Query<R> createQuery(String queryString,Class<R> resultClass)
      Description copied from interface: QueryProducer
      Create a typedQuery instance for the given HQL query string and given query result type.
      • If the query has a single item in theselect list, then the select item must be assignable to the given result type.
      • Otherwise, if there are multiple select items, then the select items will be packaged into an instance of the result type. The result type must have an appropriate constructor with parameter types matching the select items, or it must be one of the typesObject[],List,Map, orTuple.

      If a query has no explicitselect list, the select list is inferred from the given query result type:

      • if the result type is an entity type, the query must have exactly one root entity in thefrom clause, it must be assignable to the result type, and the inferred select list will contain just that entity, or
      • otherwise, the select list contains every root entity and every non-fetch joined entity, and each query result will be packaged into an instance of the result type, just as specified above.

      If a query has no explicitfrom clause, and the given result type is an entity type, the root entity is inferred to be the result type.

      PassingObject.class as the query result type is not recommended. In this special case, this method has the same semantics as the overloadQueryProducer.createQuery(String).

      The returnedQuery may be executed by callingQuery.getResultList() orQuery.getSingleResult().

      Specified by:
      createQuery in interface EntityManager
      Specified by:
      createQuery in interface QueryProducer
      Parameters:
      queryString - The HQL query
      resultClass - TheClass object representing the query result type, which should not beObject.class
      Returns:
      TheQuery instance for manipulation and execution
      See Also:
    • createQuery

      <R> Query<R> createQuery(TypedQueryReference<R> typedQueryReference)
      Description copied from interface: QueryProducer
      Create a typedQuery instance for the given typed query reference.
      Specified by:
      createQuery in interface EntityManager
      Specified by:
      createQuery in interface QueryProducer
      Parameters:
      typedQueryReference - the type query reference
      Returns:
      TheQuery instance for execution
      See Also:
    • createQuery

      @DeprecatedQuery createQuery(String queryString)
      Deprecated.
      Description copied from interface: QueryProducer
      Create aQuery instance for the given HQL query, or HQL insert, update, or delete statement.

      If a query has no explicitselect list, the select list is inferred:

      • if there is exactly one root entity in thefrom clause, and it has no non-fetch joins, then that root entity is the only element of the select list, or
      • if there is an entity with the aliasthis, then that entity is the only element of the select list, or
      • otherwise, the query is considered ambiguous, and this method throws aSemanticException.

      The query must have an explicitfrom clause, which can never be inferred.

      Specified by:
      createQuery in interface EntityManager
      Specified by:
      createQuery in interface QueryProducer
      Parameters:
      queryString - The HQL query
      Returns:
      TheQuery instance for manipulation and execution
      See Also:
    • createNamedQuery

      <R> Query<R> createNamedQuery(String name,Class<R> resultClass)
      Description copied from interface: QueryProducer
      Create a typedQuery instance for the given named query. The named query might be defined in HQL or in native SQL.
      Specified by:
      createNamedQuery in interface EntityManager
      Specified by:
      createNamedQuery in interface QueryProducer
      Parameters:
      name - the name of a query defined in metadata
      resultClass - the type of the query result
      Returns:
      TheQuery instance for manipulation and execution
      See Also:
    • createNamedQuery

      @DeprecatedQuery createNamedQuery(String name)
      Deprecated.
      Description copied from interface: QueryProducer
      Create a typedQuery instance for the given named query. The named query might be defined in HQL or in native SQL.
      Specified by:
      createNamedQuery in interface EntityManager
      Specified by:
      createNamedQuery in interface QueryProducer
      Parameters:
      name - the name of a predefined named query
      Returns:
      TheQuery instance for manipulation and execution
      See Also:
    • createQuery

      <R> Query<R> createQuery(CriteriaQuery<R> criteriaQuery)
      Description copied from interface: QueryProducer
      Create aQuery for the given JPACriteriaQuery.
      Specified by:
      createQuery in interface EntityManager
      Specified by:
      createQuery in interface QueryProducer
    • createQuery

      @Deprecated(since="6.0")Query createQuery(CriteriaDelete deleteQuery)
      Create aQuery for the given JPACriteriaDelete.
      Specified by:
      createQuery in interface EntityManager
      Specified by:
      createQuery in interface QueryProducer
    • createQuery

      @Deprecated(since="6.0")Query createQuery(CriteriaUpdate updateQuery)
      Create aQuery for the given JPACriteriaUpdate.
      Specified by:
      createQuery in interface EntityManager
      Specified by:
      createQuery in interface QueryProducer
    • unwrap

      default <T> T unwrap(Class<T> type)
      Description copied from interface: SharedSessionContract
      Return an object of the specified type to allow access to a provider-specific API.
      Specified by:
      unwrap in interface EntityManager
      Specified by:
      unwrap in interface SharedSessionContract
      Parameters:
      type - the class of the object to be returned. This is usually either the underlying class implementingSharedSessionContract or an interface it implements.
      Returns:
      an instance of the specified class