Interface SessionFactory
- All Superinterfaces:
AutoCloseable,EntityManagerFactory,Referenceable,Serializable
- All Known Subinterfaces:
SessionFactoryImplementor
- All Known Implementing Classes:
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 withconfiguration 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 obtainsessions. Typically, a program has a singleSessionFactory instance, and must obtain a newSession instance from the factory each time it services a client request. It is then also responsible fordestroying the session at the end of the client request.
TheinSession(java.util.function.Consumer<? super org.hibernate.Session>) andinTransaction(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 callSharedSessionContract.close() andEntityTransaction.commit().
Alternatively,getCurrentSession() provides support for the notion of contextually-scoped sessions, where an implementation of the SPI interfaceCurrentSessionContext is responsible for creating, scoping, and destroying sessions.
Depending on how Hibernate is configured, theSessionFactory 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 aSessionFactory 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
SessionFactoryhas 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 factoryexposes a
Statisticsobject 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 interfaceEntityManagerFactorywhichSessionFactoryinherits. Of course, these methods are usually called at the time theEntityManagerFactoryis created. It's difficult to imagine a motivation to call either method later, when the factory already has active sessions.
TheSessionFactory exposes part of the information in the runtime metamodel via aninstance of the JPA-definedMetamodel. This object is sometimes used in a sophisticated way by libraries or frameworks to implement generic concerns involving entity classes.
When Hibernate Processor is used, elements of this metamodel may also be obtained in a typesafe way, via the generated metamodel classes. For an entity classBook, the generatedBook_ class has:
- a single member named
class_of typeEntityType<Book>, and - a member for each persistent attribute of
Book, for example,titleof typeSingularAttribute<Book,String>.
Use of these statically-typed metamodel references is the preferred way of working with thecriteria query API, and withEntityGraphs.
The factory alsoprovides aSchemaManager which allows, as a convenience for writing tests:
- programmaticschema export andschema removal,
- schemavalidation, and
- an operation forcleaning up data left behind by tests.
Finally, the factoryprovides aHibernateCriteriaBuilder, an extension to the JPA-defined interfaceCriteriaBuilder, which may be used to constructcriteria queries.
EverySessionFactory is a JPAEntityManagerFactory. Furthermore, when Hibernate is acting as the JPA persistence provider, the methodEntityManagerFactory.unwrap(Class) may be used to obtain the underlyingSessionFactory.
The very simplest way to obtain a newSessionFactory is using aConfiguration orHibernatePersistenceConfiguration.
- See Also:
Method Summary
Modifier and TypeMethodDescription<R> TypedQueryReference<R>addNamedQuery(String name,TypedQuery<R> query) Add or override the definition of a named query, returning areference to the query.voidclose()Destroy thisSessionFactoryand release all its resources, including caches and connection pools.default booleanDetermine if there is a fetch profile definition registered under the given name.default <T> RootGraph<T>createEntityGraph(Class<T> entityType) Create anEntityGraphfor the given entity type.Create a newSession.createEntityManager(SynchronizationType synchronizationType) Create a newSession, with the givensynchronization type.createEntityManager(SynchronizationType synchronizationType,Map<?, ?> map) createEntityManager(Map<?, ?> map) Create a newSession, with the givenproperties.createGraphForDynamicEntity(String entityName) Create anEntityGraphwhich may be used from loading adynamic entity withEntityManager.find(EntityGraph, Object, FindOption...).RootGraph<?>findEntityGraphByName(String name) Return the rootEntityGraphwith the given name, ornullif there is no graph with the given name.<T> List<EntityGraph<? super T>>findEntityGraphsByType(Class<T> entityClass) Return allEntityGraphs registered for the given entity type.default <R> RfromSession(Function<? superSession, R> action) Open aSessionand use it to obtain a value.default <R> RfromStatelessSession(Function<? superStatelessSession, R> action) Open aStatelessSessionand use it to obtain a value.default <R> RfromStatelessTransaction(Function<? superStatelessSession, R> action) Open aStatelessSessionand use it to obtain a value within the bounds of a transaction.default <R> RfromTransaction(Function<? superSession, R> action) Open aSessionand use it to obtain a value within the bounds of a transaction.getCache()Obtain direct access to the underlying cache regions.Obtains thecurrent session, an instance ofSessionimplicitly 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.There is no plan to remove this operation, but its use should be avoided sinceFilterDefinitionis an SPI type, and so this operation is a layer-breaker.The JNDI name, used to bind theSessionFactoryto JNDI.getName()The name assigned to thisSessionFactory, if any.ASchemaManagerwith 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 sinceSessionFactoryOptionsis an SPI type, and so this operation is a layer-breaker.Retrieve thestatistics for this factory.default voidOpen aSessionand use it to perform an action.default voidinStatelessSession(Consumer<? superStatelessSession> action) Open aStatelessSessionand use it to perform an action.default voidinStatelessTransaction(Consumer<? superStatelessSession> action) Open aStatelessSessionand use it to perform an action within the bounds of a transaction.default voidinTransaction(Consumer<? superSession> action) Open aSessionand use it to perform an action within the bounds of a transaction.booleanisClosed()Is this factory already closed?Open aSession.Open a new stateless session.openStatelessSession(Connection connection) Open a new stateless session, utilizing the specified JDBCConnection.default <T> RootGraph<T>parseEntityGraph(CharSequence graphText) Creates a RootGraph based on the passed string representation.default <T> RootGraph<T>parseEntityGraph(Class<T> rootEntityClass,CharSequence graphText) Creates a RootGraph for the givenrootEntityClassand parses the graph text into it.default <T> RootGraph<T>parseEntityGraph(String rootEntityName,CharSequence graphText) Creates a RootGraph for the givenrootEntityNameand parses the graph text into it.Obtain asession builder for creating new instances ofSessionwith certain customized options.Obtain aStatelessSessionbuilder.Methods inherited from interface jakarta.persistence.EntityManagerFactory
addNamedEntityGraph,addNamedQuery,callInTransaction,getMetamodel,getNamedEntityGraphs,getNamedQueries,getPersistenceUnitUtil,getProperties,getTransactionType,isOpen,runInTransaction,unwrapMethods inherited from interface javax.naming.Referenceable
getReference
Method Details
getJndiName
String getJndiName()The JNDI name, used to bind theSessionFactoryto JNDI.withOptions
SessionBuilder withOptions()Obtain asession builder for creating new instances ofSessionwith certain customized options.- Returns:
- The session builder
openSession
Open aSession.Any JDBC
connectionwill be obtained lazily from theConnectionProvideras 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 thecurrent session, an instance ofSessionimplicitly 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
CurrentSessionContextis explicitly configured, but JTA support is enabled, thenJTASessionContextis 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 aStatelessSessionbuilder.- Returns:
- The stateless session builder
openStatelessSession
StatelessSession openStatelessSession()Open a new stateless session.- Returns:
- The new stateless session.
openStatelessSession
Open a new stateless session, utilizing the specified JDBCConnection.- Parameters:
connection- Connection provided by the application.- Returns:
- The new stateless session.
inSession
Open aSessionand use it to perform an action.inStatelessSession
Open aStatelessSessionand use it to perform an action.- Since:
- 6.3
inTransaction
Open aSessionand 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 aStatelessSessionand use it to perform an action within the bounds of a transaction.- Since:
- 6.3
fromSession
Open aSessionand use it to obtain a value.fromStatelessSession
Open aStatelessSessionand use it to obtain a value.- Since:
- 6.3
fromTransaction
Open aSessionand 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 aStatelessSessionand use it to obtain a value within the bounds of a transaction.- Since:
- 6.3
createEntityManager
Session createEntityManager()Create a newSession.- Specified by:
createEntityManagerin interfaceEntityManagerFactory
createEntityManager
Create a newSession, with the givenproperties.- Specified by:
createEntityManagerin interfaceEntityManagerFactory
createEntityManager
Create a newSession, with the givensynchronization type.- Specified by:
createEntityManagerin interfaceEntityManagerFactory- Throws:
IllegalStateException- if the persistence unit hasresource-local transaction management
createEntityManager
- Specified by:
createEntityManagerin interfaceEntityManagerFactory- Throws:
IllegalStateException- if the persistence unit hasresource-local transaction management
getStatistics
Statistics getStatistics()Retrieve thestatistics for this factory.- Returns:
- The statistics.
getSchemaManager
SchemaManager getSchemaManager()ASchemaManagerwith the same default catalog and schema as pooled connections belonging to this factory. Intended mostly as a convenience for writing tests.- Specified by:
getSchemaManagerin interfaceEntityManagerFactory- Since:
- 6.2
getCriteriaBuilder
HibernateCriteriaBuilder getCriteriaBuilder()- Specified by:
getCriteriaBuilderin interfaceEntityManagerFactory- See Also:
close
Destroy thisSessionFactoryand release all its resources, including caches and connection pools.It is the responsibility of the application to ensure that there are no opensessions before calling this method as the impact on thosesessions is indeterminate.
No-ops if alreadyclosed.
- Specified by:
closein interfaceAutoCloseable- Specified by:
closein 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:
getCachein interfaceEntityManagerFactory- Returns:
- The direct cache access API.
findEntityGraphsByType
Return allEntityGraphs registered for the given entity type.findEntityGraphByName
Return the rootEntityGraphwith the given name, ornullif there is no graph with the given name.- Parameters:
name- the name given to someNamedEntityGraph- Returns:
- an instance of
RootGraph - See Also:
createEntityGraph
Create anEntityGraphfor the given entity type.- Parameters:
entityType- The entity type for the graph- Since:
- 7.0
- See Also:
createGraphForDynamicEntity
Create anEntityGraphwhich may be used from loading adynamic entity withEntityManager.find(EntityGraph, Object, FindOption...).This allows a dynamic entity to be loaded without the need for a cast.
var MyDynamicEntity_ = factory.createGraphForDynamicEntity("MyDynamicEntity"); Map<String,?> myDynamicEntity = session.find(MyDynamicEntity_, id);- Parameters:
entityName- The name of the dynamic entity- Since:
- 7.0
- See Also:
- API Note:
- Dynamic entities are normally defined using XML mappings.
parseEntityGraph
Creates a RootGraph for the givenrootEntityClassand parses the graph text into it.- Parameters:
rootEntityClass- The entity class to use as the base of the created root-graphgraphText- The textual representation of the graph- Throws:
InvalidGraphException- if the textual representation is invalid.- Since:
- 7.0
- See Also:
- API Note:
- The string representation is expected to just be an attribute list. E.g.
"title, isbn, author(name, books)"
parseEntityGraph
Creates a RootGraph for the givenrootEntityNameand parses the graph text into it.- Parameters:
rootEntityName- The name of the entity to use as the base of the created root-graphgraphText- The textual representation of the graph- Throws:
InvalidGraphException- if the textual representation is invalid.- Since:
- 7.0
- See Also:
- API Note:
- The string representation is expected to just be an attribute list. E.g.
"title, isbn, author(name, books)"
parseEntityGraph
Creates a RootGraph based on the passed string representation. Here, the string representation is expected to include the root entity name.- Parameters:
graphText- The textual representation of the graph- Throws:
InvalidGraphException- if the textual representation is invalid.- Since:
- 7.0
- API Note:
- The string representation is expected to an attribute list prefixed with the name of the root entity. E.g.
"Book: title, isbn, author(name, books)"
getDefinedFilterNames
Obtain the set of names of alldefined filters.- Returns:
- The set of filter names given by
FilterDefannotations
getFilterDefinition
@Deprecated(since="6.2")FilterDefinition getFilterDefinition(String filterName) throwsHibernateException Deprecated.There is no plan to remove this operation, but its use should be avoided sinceFilterDefinitionis 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
FetchProfileannotations. - 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.
addNamedQuery
Add or override the definition of a named query, returning areference to the query. Settings such as first and max results, hints, flush mode, cache mode, timeout, and lock options are preserved as part of the named query definition. Any arguments bound to query parameters are discarded.- Parameters:
name- the name to be assigned to the queryquery- the query, including first and max results, hints, flush mode, cache mode, timeout, and lock options- Since:
- 7.0
- See Also:
getName
String getName()The name assigned to thisSessionFactory, if any.- When bootstrapping via JPA, this is the persistence unit name.
- Otherwise, the name may be specified by the configuration property"hibernate.session_factory_name".
If"hibernate.session_factory_name_is_jndi" is enabled, then this name is used to bind this object to JNDI, unless"hibernate.session_factory_jndi_name" is also specified.
getSessionFactoryOptions
Deprecated.There is no plan to remove this operation, but its use should be avoided sinceSessionFactoryOptionsis an SPI type, and so this operation is a layer-breaker.Get theoptions used to build this factory.- Returns:
- The special options used to build the factory.