Interface SessionFactory
-
- All Superinterfaces:
AutoCloseable
,Closeable
,jakarta.persistence.EntityManagerFactory
,Referenceable
,Serializable
- All Known Subinterfaces:
SessionFactoryImplementor
- All Known Implementing Classes:
SessionFactoryDelegatingImpl
,SessionFactoryImpl
public interface SessionFactory extends jakarta.persistence.EntityManagerFactory, Referenceable, Serializable, Closeable
ASessionFactory
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 singleSessionFactory
instance, and must obtain a newSession
instance from the factory each time it services a client request.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 theSessionFactory
is created. Of course, anySessionFactory
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 itexposes 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.
SessionFactory
exposes part of the information in the runtime metamodel via an instance of the JPA-definedMetamodel
. This object is sometimes used in a sophisticated way by libraries or frameworks to implement generic concerns involving entity classes.The factory also provides a
SchemaManager
which allows, as a convenience for writing tests:- programmatic schema export and schema removal, and
- an operation for cleaning up data left behind by tests.
Every
SessionFactory
is a JPAEntityManagerFactory
. Furthermore, when Hibernate is acting as the JPA persistence provider, the methodEntityManagerFactory.unwrap(Class)
may be used to obtain the underlyingSessionFactory
.- See Also:
Session
,Configuration
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static class
SessionFactory.TransactionManagementException
-
Method Summary
All Methods Instance Methods Abstract Methods Default Methods Deprecated Methods Modifier and Type Method Description void
close()
Destroy thisSessionFactory
and release all its resources, including caches and connection pools.default boolean
containsFetchProfileDefinition(String name)
Determine if there is a fetch profile definition registered under the given name.RootGraph<?>
findEntityGraphByName(String name)
Return the rootEntityGraph
with the given name, ornull
if there is no graph with the given name.<T> List<jakarta.persistence.EntityGraph<? super T>>
findEntityGraphsByType(Class<T> entityClass)
Return allEntityGraph
s registered for the given entity type.default <R> R
fromSession(Function<Session,R> action)
Open aSession
and use it to obtain a value.default <R> R
fromTransaction(Function<Session,R> action)
Open aSession
and use it to perform an action within the bounds of a transaction.Cache
getCache()
Obtain direct access to the underlying cache regions.Session
getCurrentSession()
Obtains the current session, an instance ofSession
implicitly associated with some context.Set<String>
getDefinedFetchProfileNames()
Obtain the set of names of alldefined fetch profiles
.Set<String>
getDefinedFilterNames()
Obtain the set of names of alldefined filters
.FilterDefinition
getFilterDefinition(String filterName)
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.SchemaManager
getSchemaManager()
ASchemaManager
with the same default catalog and schema as pooled connections belonging to this factory.SessionFactoryOptions
getSessionFactoryOptions()
Get the special options used to build the factory.Statistics
getStatistics()
Retrieve the statistics for this factory.default void
inSession(Consumer<Session> action)
Open aSession
and use it to perform an action.default void
inTransaction(Consumer<Session> action)
Open aSession
and use it to perform an action within the bounds of a transaction.boolean
isClosed()
Is this factory already closed?Session
openSession()
Open aSession
.StatelessSession
openStatelessSession()
Open a new stateless session.StatelessSession
openStatelessSession(Connection connection)
Open a new stateless session, utilizing the specified JDBCConnection
.SessionBuilder
withOptions()
Obtain a session builder for creating newSession
s with certain customized options.StatelessSessionBuilder
withStatelessOptions()
Obtain aStatelessSession
builder.-
Methods inherited from interface jakarta.persistence.EntityManagerFactory
addNamedEntityGraph, addNamedQuery, createEntityManager, createEntityManager, createEntityManager, createEntityManager, getCriteriaBuilder, getMetamodel, getPersistenceUnitUtil, getProperties, isOpen, unwrap
-
Methods inherited from interface javax.naming.Referenceable
getReference
-
-
-
-
Method Detail
-
getSessionFactoryOptions
SessionFactoryOptions getSessionFactoryOptions()
Get the special options used to build the factory.- Returns:
- The special options used to build the factory.
-
withOptions
SessionBuilder withOptions()
Obtain a session builder for creating newSession
s with certain customized options.- Returns:
- The session builder
-
openSession
Session openSession() throws HibernateException
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.
-
getCurrentSession
Session getCurrentSession() throws HibernateException
Obtains the current session, an instance ofSession
implicitly associated with some context. 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 is configured, thenJTASessionContext
is used.- Returns:
- The current session.
- Throws:
HibernateException
- Indicates an issue locating a suitable current session.
-
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
StatelessSession openStatelessSession(Connection connection)
Open a new stateless session, utilizing the specified JDBCConnection
.- Parameters:
connection
- Connection provided by the application.- Returns:
- The created stateless session.
-
inSession
default void inSession(Consumer<Session> action)
Open aSession
and use it to perform an action.
-
inTransaction
default void inTransaction(Consumer<Session> action)
Open aSession
and use it to perform an action within the bounds of a transaction.
-
fromSession
default <R> R fromSession(Function<Session,R> action)
Open aSession
and use it to obtain a value.
-
fromTransaction
default <R> R fromTransaction(Function<Session,R> action)
Open aSession
and use it to perform an action within the bounds of a transaction.
-
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.- Since:
- 6.2
-
close
void close() throws HibernateException
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 interfaceCloseable
- Specified by:
close
in interfacejakarta.persistence.EntityManagerFactory
- 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 interfacejakarta.persistence.EntityManagerFactory
- Returns:
- The direct cache access API.
-
findEntityGraphsByType
<T> List<jakarta.persistence.EntityGraph<? super T>> findEntityGraphsByType(Class<T> entityClass)
Return allEntityGraph
s registered for the given entity type.- See Also:
EntityManagerFactory.addNamedEntityGraph(java.lang.String, jakarta.persistence.EntityGraph<T>)
-
findEntityGraphByName
RootGraph<?> findEntityGraphByName(String name)
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:
EntityManagerFactory.addNamedEntityGraph(java.lang.String, jakarta.persistence.EntityGraph<T>)
-
getDefinedFilterNames
Set<String> 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
Set<String> 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
default boolean containsFetchProfileDefinition(String name)
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.
-
-