Top Description Methods
org.hibernate

public Interface SessionFactory

extends EntityManagerFactory, Referenceable, Serializable, Closeable
Known Direct Subinterfaces
org.hibernate.engine.spi.SessionFactoryImplementor
Known Direct Implementers
org.hibernate.engine.spi.SessionFactoryDelegatingImpl
Imports
java.io.Serializable, java.sql.Connection, java.util.List, .Set, java.util.function.Consumer, .Function, javax.naming.Referenceable, org.hibernate.boot.spi.SessionFactoryOptions, org.hibernate.engine.spi.FilterDefinition, org.hibernate.graph.RootGraph, org.hibernate.query.criteria.HibernateCriteriaBuilder, org.hibernate.relational.SchemaManager, org.hibernate.stat.Statistics, jakarta.persistence.EntityGraph, .EntityManagerFactory

A SessionFactory represents an "instance" of Hibernate: it maintains the runtime metamodel representing persistent entities, their attributes, their associations, and their mappings to relational database tables, along with configuration that affects the runtime behavior of Hibernate, and instances of services that Hibernate needs to perform its duties.

Crucially, this is where a program comes to obtain sessions. Typically, a program has a single SessionFactory instance, and must obtain a new Session instance from the factory each time it services a client request. It is then also responsible for destroying the session at the end of the client request.

The inSession and inTransaction methods provide a convenient way to obtain a session, with or without starting a transaction, and have it cleaned up automatically, relieving the program of the need to explicitly call Session#close() and Transaction#commit().

Alternatively, getCurrentSession() provides support for the notion of contextually-scoped sessions, where an implementation of the SPI interface org.hibernate.context.spi.CurrentSessionContext is responsible for creating, scoping, and destroying sessions.

Depending on how Hibernate is configured, the SessionFactory itself might be responsible for the lifecycle of pooled JDBC connections and transactions, or it may simply act as a client for a connection pool or transaction manager provided by a container environment.

The internal state of a SessionFactory is considered in some sense "immutable". While it interacts with stateful services like JDBC connection pools, such state changes are never visible to its clients. In particular, the runtime metamodel representing the entities and their O/R mappings is fixed as soon as the SessionFactory is created. Of course, any SessionFactory is threadsafe.

There are some interesting exceptions to this principle:

The SessionFactory exposes part of the information in the runtime metamodel via an instance of the JPA-defined jakarta.persistence.metamodel.Metamodel. This object is sometimes used in a sophisticated way by libraries or frameworks to implement generic concerns involving entity classes.

When the Metamodel Generator is used, elements of this metamodel may also be obtained in a typesafe way, via the generated metamodel classes. For an entity class Book, the generated Book_ class has:

Use of these statically-typed metamodel references is the preferred way of working with the criteria query API, and with EntityGraphs.

The factory also provides a SchemaManager which allows, as a convenience for writing tests:

Finally, the factory provides a HibernateCriteriaBuilder, an extension to the JPA-defined interface jakarta.persistence.criteria.CriteriaBuilder, which may be used to construct criteria queries.

Every SessionFactory is a JPA EntityManagerFactory. Furthermore, when Hibernate is acting as the JPA persistence provider, the method EntityManagerFactory#unwrap(Class) may be used to obtain the underlying SessionFactory.

The very simplest way to obtain a new SessionFactory is using a org.hibernate.cfg.Configuration.

Authors
Gavin King, Steve Ebersole
See Also
Session, org.hibernate.cfg.Configuration

Method Summary

Modifier and TypeMethod and Description
public void
close()

Redeclares jakarta.persistence.EntityManagerFactory.close, java.io.Closeable.close.

Destroy this SessionFactory and release all its resources, including caches and connection pools.
public default boolean

Returns:

True if there is such a fetch profile; false otherwise.
containsFetchProfileDefinition
(String
The name to check
name
)

Determine if there is a fetch profile definition registered under the given name.

public RootGraph<?>

Returns:

an instance of RootGraph
findEntityGraphByName
(String name)

Return the root EntityGraph with the given name, or null if there is no graph with the given name.

public <T> List<EntityGraph<? super T>>
findEntityGraphsByType(Class<T> entityClass)

Return all EntityGraphs registered for the given entity type.

public default <R> R
fromSession(Function<Session, R> action)

Open a Session and use it to obtain a value.

public default <R> R
fromStatelessSession(Function<StatelessSession, R> action)

Open a StatelessSession and use it to obtain a value.

public default <R> R
fromStatelessTransaction(Function<StatelessSession, R> action)

Open a StatelessSession and use it to obtain a value within the bounds of a transaction.

public default <R> R
fromTransaction(Function<Session, R> action)

Open a Session and use it to obtain a value within the bounds of a transaction.

public Cache

Returns:

The direct cache access API.
getCache
()

Redeclares jakarta.persistence.EntityManagerFactory.getCache.

Obtain direct access to the underlying cache regions.
public HibernateCriteriaBuilder
public Session

Returns:

The current session.
getCurrentSession
()

Obtains the current session, an instance of Session implicitly associated with some context or scope.

public Set<String>

Returns:

The set of fetch profile names given by org.hibernate.annotations.FetchProfile annotations.
getDefinedFetchProfileNames
()

Obtain the set of names of all defined fetch profiles.

public Set<String>

Returns:

The set of filter names given by org.hibernate.annotations.FilterDef annotations
getDefinedFilterNames
()

Obtain the set of names of all defined filters.

public FilterDefinition

Returns:

The filter definition.
getFilterDefinition
(String
The name of the filter for which to obtain the definition.
filterName
)

Deprecated since 6.2. There is no plan to remove this operation, but its use should be avoided since FilterDefinition is an SPI type, and so this operation is a layer-breaker.
Obtain the definition of a filter by name.
public SchemaManager
getSchemaManager()

A SchemaManager with the same default catalog and schema as pooled connections belonging to this factory.

public SessionFactoryOptions

Returns:

The special options used to build the factory.
getSessionFactoryOptions
()

Deprecated since 6.2. There is no plan to remove this operation, but its use should be avoided since SessionFactoryOptions is an SPI type, and so this operation is a layer-breaker.
Get the options used to build this factory.
public Statistics

Returns:

The statistics.
getStatistics
()

Retrieve the statistics for this factory.

public default void
inSession(Consumer<Session> action)

Open a Session and use it to perform an action.

public default void
inStatelessSession(Consumer<StatelessSession> action)

Open a StatelessSession and use it to perform an action.

public default void
inStatelessTransaction(Consumer<StatelessSession> action)

Open a StatelessSession and use it to perform an action within the bounds of a transaction.

public default void
inTransaction(Consumer<Session> action)

Open a Session and use it to perform an action within the bounds of a transaction.

public boolean

Returns:

True if this factory is already closed; false otherwise.
isClosed
()

Is this factory already closed?

public Session

Returns:

The created session.
openSession
()

Open a Session.

public StatelessSession

Returns:

The created stateless session.
openStatelessSession
()

Open a new stateless session.

public StatelessSession

Returns:

The created stateless session.
openStatelessSession
(Connection
Connection provided by the application.
connection
)

Open a new stateless session, utilizing the specified JDBC Connection.

public SessionBuilder

Returns:

The session builder
withOptions
()

Obtain a session builder for creating new Sessions with certain customized options.

public StatelessSessionBuilder

Returns:

The stateless session builder
withStatelessOptions
()

Obtain a StatelessSession builder.

Inherited from jakarta.persistence.EntityManagerFactory:
addNamedEntityGraphaddNamedQuerycreateEntityManagercreateEntityManagercreateEntityManagercreateEntityManagergetMetamodelgetPersistenceUnitUtilgetPropertiesisOpenunwrap
Inherited from javax.naming.Referenceable:
getReference

Method Detail

closeback to summary
public void close() throws HibernateException

Redeclares jakarta.persistence.EntityManagerFactory.close, java.io.Closeable.close.

Destroy this SessionFactory and release all its resources, including caches and connection pools.

It is the responsibility of the application to ensure that there are no open sessions before calling this method as the impact on those sessions is indeterminate.

No-ops if already closed.

Exceptions
HibernateException:
Indicates an issue closing the factory.
containsFetchProfileDefinitionback to summary
public default boolean containsFetchProfileDefinition(String name)

Determine if there is a fetch profile definition registered under the given name.

Parameters
name:String

The name to check

Returns:boolean

True if there is such a fetch profile; false otherwise.

findEntityGraphByNameback to summary
public RootGraph<?> findEntityGraphByName(String name)

Return the root EntityGraph with the given name, or null if there is no graph with the given name.

Parameters
name:String

the name given to some jakarta.persistence.NamedEntityGraph

Returns:RootGraph<?>

an instance of RootGraph

See Also
addNamedEntityGraph
findEntityGraphsByTypeback to summary
public <T> List<EntityGraph<? super T>> findEntityGraphsByType(Class<T> entityClass)

Return all EntityGraphs registered for the given entity type.

See Also
addNamedEntityGraph
fromSessionback to summary
public default <R> R fromSession(Function<Session, R> action)

Open a Session and use it to obtain a value.

fromStatelessSessionback to summary
public default <R> R fromStatelessSession(Function<StatelessSession, R> action)

Open a StatelessSession and use it to obtain a value.

Since
6.3
fromStatelessTransactionback to summary
public default <R> R fromStatelessTransaction(Function<StatelessSession, R> action)

Open a StatelessSession and use it to obtain a value within the bounds of a transaction.

Since
6.3
fromTransactionback to summary
public default <R> R fromTransaction(Function<Session, R> action)

Open a Session and use it to obtain a value within the bounds of a transaction.

getCacheback to summary
public Cache getCache()

Redeclares jakarta.persistence.EntityManagerFactory.getCache.

Obtain direct access to the underlying cache regions.

Returns:Cache

The direct cache access API.

Annotations
@Override
getCriteriaBuilderback to summary
public HibernateCriteriaBuilder getCriteriaBuilder()

Redeclares jakarta.persistence.EntityManagerFactory.getCriteriaBuilder.

Obtain a HibernateCriteriaBuilder which may be used to construct criteria queries.

Returns:HibernateCriteriaBuilder

Doc from jakarta.persistence.EntityManagerFactory.getCriteriaBuilder.

CriteriaBuilder instance

Annotations
@Override
See Also
SharedSessionContract#getCriteriaBuilder()
getCurrentSessionback to summary
public Session getCurrentSession() throws HibernateException

Obtains the current session, an instance of Session implicitly associated with some context or scope. For example, the session might be associated with the current thread, or with the current JTA transaction.

The context used for scoping the current session (that is, the definition of what precisely "current" means here) is determined by an implementation of org.hibernate.context.spi.CurrentSessionContext. An implementation may be selected using the configuration property hibernate.current_session_context_class.

If no org.hibernate.context.spi.CurrentSessionContext is explicitly configured, but JTA support is enabled, then org.hibernate.context.internal.JTASessionContext is used, and the current session is scoped to the active JTA transaction.

Returns:Session

The current session.

Exceptions
HibernateException:
Indicates an issue locating a suitable current session.
See Also
org.hibernate.context.spi.CurrentSessionContext, org.hibernate.cfg.AvailableSettings#CURRENT_SESSION_CONTEXT_CLASS
getDefinedFetchProfileNamesback to summary
public Set<String> getDefinedFetchProfileNames()

Obtain the set of names of all defined fetch profiles.

Returns:Set<String>

The set of fetch profile names given by org.hibernate.annotations.FetchProfile annotations.

Since
6.2
getDefinedFilterNamesback to summary
public Set<String> getDefinedFilterNames()

Obtain the set of names of all defined filters.

Returns:Set<String>

The set of filter names given by org.hibernate.annotations.FilterDef annotations

getFilterDefinitionback to summary
public FilterDefinition getFilterDefinition(String filterName) throws HibernateException

Deprecated

since 6.2.

There is no plan to remove this operation, but its use should be avoided since FilterDefinition is an SPI type, and so this operation is a layer-breaker.

Obtain the definition of a filter by name.

Parameters
filterName:String

The name of the filter for which to obtain the definition.

Returns:FilterDefinition

The filter definition.

Annotations
@Deprecated
since:6.2
Exceptions
HibernateException:
If no filter defined with the given name.
getSchemaManagerback to summary
public SchemaManager getSchemaManager()

A SchemaManager with the same default catalog and schema as pooled connections belonging to this factory. Intended mostly as a convenience for writing tests.

Since
6.2
getSessionFactoryOptionsback to summary
public SessionFactoryOptions getSessionFactoryOptions()

Deprecated

since 6.2.

There is no plan to remove this operation, but its use should be avoided since SessionFactoryOptions is an SPI type, and so this operation is a layer-breaker.

Get the options used to build this factory.

Returns:SessionFactoryOptions

The special options used to build the factory.

Annotations
@Deprecated
since:6.2
getStatisticsback to summary
public Statistics getStatistics()

Retrieve the statistics for this factory.

Returns:Statistics

The statistics.

inSessionback to summary
public default void inSession(Consumer<Session> action)

Open a Session and use it to perform an action.

inStatelessSessionback to summary
public default void inStatelessSession(Consumer<StatelessSession> action)

Open a StatelessSession and use it to perform an action.

Since
6.3
inStatelessTransactionback to summary
public default void inStatelessTransaction(Consumer<StatelessSession> action)

Open a StatelessSession and use it to perform an action within the bounds of a transaction.

Since
6.3
inTransactionback to summary
public default void inTransaction(Consumer<Session> action)

Open a Session and use it to perform an action within the bounds of a transaction.

isClosedback to summary
public boolean isClosed()

Is this factory already closed?

Returns:boolean

True if this factory is already closed; false otherwise.

openSessionback to summary
public Session openSession() throws HibernateException

Open a Session.

Any JDBC connection will be obtained lazily from the org.hibernate.engine.jdbc.connections.spi.ConnectionProvider as needed to perform requested work.

Returns:Session

The created session.

Exceptions
HibernateException:
Indicates a problem opening the session; pretty rare here.
openStatelessSessionback to summary
public StatelessSession openStatelessSession()

Open a new stateless session.

Returns:StatelessSession

The created stateless session.

openStatelessSessionback to summary
public StatelessSession openStatelessSession(Connection connection)

Open a new stateless session, utilizing the specified JDBC Connection.

Parameters
connection:Connection

Connection provided by the application.

Returns:StatelessSession

The created stateless session.

withOptionsback to summary
public SessionBuilder withOptions()

Obtain a session builder for creating new Sessions with certain customized options.

Returns:SessionBuilder

The session builder

withStatelessOptionsback to summary
public StatelessSessionBuilder withStatelessOptions()

Obtain a StatelessSession builder.

Returns:StatelessSessionBuilder

The stateless session builder