Interface SessionFactory
- All Superinterfaces:
AutoCloseable
,EntityManagerFactory
,Referenceable
,Serializable
- All Known Subinterfaces:
SessionFactoryImplementor
- All Known Implementing Classes:
MockSessionFactory
,ProcessorSessionFactory
,SessionFactoryDelegatingImpl
,SessionFactoryImpl
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(java.util.function.Consumer<? super org.hibernate.Session>)
and inTransaction(java.util.function.Consumer<? super org.hibernate.Session>)
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 SharedSessionContract.close()
and EntityTransaction.commit()
.
Alternatively, getCurrentSession()
provides support for the notion
of contextually-scoped sessions, where an implementation of the SPI interface
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:
- Each
SessionFactory
has its own isolated second-level cache, shared between the sessions it creates, and it exposes the cache to clients as a stateful object with entries that may be queried and managed directly. - Similarly, the factory exposes a
Statistics
object which accumulates information summarizing the activity of sessions created by the factory. It provides statistics about interactions with JDBC and with the second-level cache. - Somewhat regrettably, The JPA 2.1 specification chose to locate the
operations
EntityManagerFactory.addNamedQuery(String, jakarta.persistence.Query)
andEntityManagerFactory.addNamedEntityGraph(String, EntityGraph)
on the interfaceEntityManagerFactory
whichSessionFactory
inherits. Of course, these methods are usually called at the time theEntityManagerFactory
is created. It's difficult to imagine a motivation to call either method later, when the factory already has active sessions.
The SessionFactory
exposes part of the information in the runtime
metamodel via an instance of the JPA-defined
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:
- a single member named
class_
of typeEntityType<Book>
, and - a member for each persistent attribute of
Book
, for example,title
of typeSingularAttribute<Book,String>
.
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:
- programmatic schema export and schema removal,
- schema validation, and
- an operation for cleaning up data left behind by tests.
Finally, the factory provides a
HibernateCriteriaBuilder
, an extension to the JPA-defined interface
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
Configuration
.
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionvoid
close()
Destroy thisSessionFactory
and release all its resources, including caches and connection pools.default boolean
Determine if there is a fetch profile definition registered under the given name.Create a newSession
.createEntityManager
(SynchronizationType synchronizationType) Create a newSession
, with the given synchronization type.createEntityManager
(SynchronizationType synchronizationType, Map<?, ?> map) createEntityManager
(Map<?, ?> map) Create a newSession
, with the given properties.RootGraph<?>
findEntityGraphByName
(String name) Return the rootEntityGraph
with the given name, ornull
if there is no graph with the given name.<T> List<EntityGraph<? super T>>
findEntityGraphsByType
(Class<T> entityClass) Return allEntityGraph
s registered for the given entity type.default <R> R
fromSession
(Function<? super Session, R> action) Open aSession
and use it to obtain a value.default <R> R
fromStatelessSession
(Function<? super StatelessSession, R> action) Open aStatelessSession
and use it to obtain a value.default <R> R
fromStatelessTransaction
(Function<? super StatelessSession, R> action) Open aStatelessSession
and use it to obtain a value within the bounds of a transaction.default <R> R
fromTransaction
(Function<? super Session, R> action) Open aSession
and use it to obtain a value within the bounds of a transaction.getCache()
Obtain direct access to the underlying cache regions.Obtains the current session, an instance ofSession
implicitly associated with some context or scope.Obtain the set of names of alldefined fetch profiles
.Obtain the set of names of alldefined filters
.getFilterDefinition
(String filterName) Deprecated.The JNDI name, used to bind the SessionFactory to JNDIASchemaManager
with the same default catalog and schema as pooled connections belonging to this factory.Deprecated.There is no plan to remove this operation, but its use should be avoided sinceSessionFactoryOptions
is an SPI type, and so this operation is a layer-breaker.Retrieve the statistics for this factory.default void
Open aSession
and use it to perform an action.default void
inStatelessSession
(Consumer<? super StatelessSession> action) Open aStatelessSession
and use it to perform an action.default void
inStatelessTransaction
(Consumer<? super StatelessSession> action) Open aStatelessSession
and use it to perform an action within the bounds of a transaction.default void
inTransaction
(Consumer<? super Session> action) Open aSession
and use it to perform an action within the bounds of a transaction.boolean
isClosed()
Is this factory already closed?Open aSession
.Open a new stateless session.openStatelessSession
(Connection connection) Open a new stateless session, utilizing the specified JDBCConnection
.Obtain a session builder for creating newSession
s with certain customized options.Obtain aStatelessSession
builder.Methods inherited from interface jakarta.persistence.EntityManagerFactory
addNamedEntityGraph, addNamedQuery, callInTransaction, getMetamodel, getName, getNamedEntityGraphs, getNamedQueries, getPersistenceUnitUtil, getProperties, getTransactionType, isOpen, runInTransaction, unwrap
Methods inherited from interface javax.naming.Referenceable
getReference
-
Method Details
-
getJndiName
String getJndiName()The JNDI name, used to bind the SessionFactory to JNDI -
withOptions
SessionBuilder withOptions()Obtain a session builder for creating newSession
s with certain customized options.- Returns:
- The session builder
-
openSession
Open aSession
.Any JDBC
connection
will be obtained lazily from theConnectionProvider
as needed to perform requested work.- Returns:
- The created session.
- Throws:
HibernateException
- Indicates a problem opening the session; pretty rare here.- API Note:
- This operation is very similar to
createEntityManager()
-
getCurrentSession
Obtains the current session, an instance ofSession
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
CurrentSessionContext
. An implementation may be selected using the configuration property "hibernate.current_session_context_class".If no
CurrentSessionContext
is explicitly configured, but JTA support is enabled, thenJTASessionContext
is used, and the current session is scoped to the active JTA transaction.- Returns:
- The current session.
- Throws:
HibernateException
- Indicates an issue locating a suitable current session.- See Also:
-
withStatelessOptions
StatelessSessionBuilder withStatelessOptions()Obtain aStatelessSession
builder.- Returns:
- The stateless session builder
-
openStatelessSession
StatelessSession openStatelessSession()Open a new stateless session.- Returns:
- The created stateless session.
-
openStatelessSession
Open a new stateless session, utilizing the specified JDBCConnection
.- Parameters:
connection
- Connection provided by the application.- Returns:
- The created stateless session.
-
inSession
Open aSession
and use it to perform an action. -
inStatelessSession
Open aStatelessSession
and use it to perform an action.- Since:
- 6.3
-
inTransaction
Open aSession
and use it to perform an action within the bounds of a transaction.- API Note:
- This method competes with the JPA-defined method
EntityManagerFactory.runInTransaction(java.util.function.Consumer<jakarta.persistence.EntityManager>)
-
inStatelessTransaction
Open aStatelessSession
and use it to perform an action within the bounds of a transaction.- Since:
- 6.3
-
fromSession
Open aSession
and use it to obtain a value. -
fromStatelessSession
Open aStatelessSession
and use it to obtain a value.- Since:
- 6.3
-
fromTransaction
Open aSession
and use it to obtain a value within the bounds of a transaction.- API Note:
- This method competes with the JPA-defined method
EntityManagerFactory.callInTransaction(java.util.function.Function<jakarta.persistence.EntityManager, R>)
-
fromStatelessTransaction
Open aStatelessSession
and use it to obtain a value within the bounds of a transaction.- Since:
- 6.3
-
createEntityManager
Session createEntityManager()Create a newSession
.- Specified by:
createEntityManager
in interfaceEntityManagerFactory
-
createEntityManager
Create a newSession
, with the given properties.- Specified by:
createEntityManager
in interfaceEntityManagerFactory
-
createEntityManager
Create a newSession
, with the given synchronization type.- Specified by:
createEntityManager
in interfaceEntityManagerFactory
- Throws:
IllegalStateException
- if the persistence unit has resource-local transaction management
-
createEntityManager
- Specified by:
createEntityManager
in interfaceEntityManagerFactory
- Throws:
IllegalStateException
- if the persistence unit has resource-local transaction management
-
getStatistics
Statistics getStatistics()Retrieve the statistics for this factory.- Returns:
- The statistics.
-
getSchemaManager
SchemaManager getSchemaManager()ASchemaManager
with the same default catalog and schema as pooled connections belonging to this factory. Intended mostly as a convenience for writing tests.- Specified by:
getSchemaManager
in interfaceEntityManagerFactory
- Since:
- 6.2
-
getCriteriaBuilder
HibernateCriteriaBuilder getCriteriaBuilder()- Specified by:
getCriteriaBuilder
in interfaceEntityManagerFactory
- See Also:
-
close
Destroy thisSessionFactory
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.
- Specified by:
close
in interfaceAutoCloseable
- Specified by:
close
in interfaceEntityManagerFactory
- Throws:
HibernateException
- Indicates an issue closing the factory.
-
isClosed
boolean isClosed()Is this factory already closed?- Returns:
- True if this factory is already closed; false otherwise.
-
getCache
Cache getCache()Obtain direct access to the underlying cache regions.- Specified by:
getCache
in interfaceEntityManagerFactory
- Returns:
- The direct cache access API.
-
findEntityGraphsByType
Return allEntityGraph
s registered for the given entity type. -
findEntityGraphByName
Return the rootEntityGraph
with the given name, ornull
if there is no graph with the given name.- Parameters:
name
- the name given to someNamedEntityGraph
- Returns:
- an instance of
RootGraph
- See Also:
-
getDefinedFilterNames
Obtain the set of names of alldefined filters
.- Returns:
- The set of filter names given by
FilterDef
annotations
-
getFilterDefinition
@Deprecated(since="6.2") FilterDefinition getFilterDefinition(String filterName) throws HibernateException Deprecated.There is no plan to remove this operation, but its use should be avoided sinceFilterDefinition
is an SPI type, and so this operation is a layer-breaker.Obtain the definition of a filter by name.- Parameters:
filterName
- The name of the filter for which to obtain the definition.- Returns:
- The filter definition.
- Throws:
HibernateException
- If no filter defined with the given name.
-
getDefinedFetchProfileNames
Obtain the set of names of alldefined fetch profiles
.- Returns:
- The set of fetch profile names given by
FetchProfile
annotations. - Since:
- 6.2
-
containsFetchProfileDefinition
Determine if there is a fetch profile definition registered under the given name.- Parameters:
name
- The name to check- Returns:
- True if there is such a fetch profile; false otherwise.
-
getSessionFactoryOptions
Deprecated.There is no plan to remove this operation, but its use should be avoided sinceSessionFactoryOptions
is an SPI type, and so this operation is a layer-breaker.Get the options used to build this factory.- Returns:
- The special options used to build the factory.
-
FilterDefinition
is an SPI type, and so this operation is a layer-breaker.