Package org.springframework.orm.hibernate5

# Class LocalSessionFactoryBean

java.lang.Object
org.springframework.orm.hibernate5.HibernateExceptionTranslator
org.springframework.orm.hibernate5.LocalSessionFactoryBean

All Implemented Interfaces:
  `org.springframework.beans.factory.Aware`, `org.springframework.beans.factory.BeanFactoryAware`, `org.springframework.beans.factory.DisposableBean`, `org.springframework.beans.factory.FactoryBean<SessionFactory>`, `org.springframework.beans.factory.InitializingBean`, `org.springframework.beans.factory.SmartInitializingSingleton`, `org.springframework.context.ResourceLoaderAware`, `org.springframework.dao.support.PersistenceExceptionTranslator`

public class LocalSessionFactoryBean extends HibernateExceptionTranslator implements org.springframework.beans.factory.FactoryBean<SessionFactory>, org.springframework.context.ResourceLoaderAware, org.springframework.beans.factory.BeanFactoryAware, org.springframework.beans.factory.InitializingBean, org.springframework.beans.factory.SmartInitializingSingleton, org.springframework.beans.factory.DisposableBean
`FactoryBean` that creates a Hibernate `SessionFactory`. This is the usual way to set up a shared Hibernate SessionFactory in a Spring application context; the SessionFactory can then be passed to data access objects via dependency injection.

Compatible with Hibernate ORM 5.5/5.6, as of Spring Framework 6.0. This Hibernate-specific `LocalSessionFactoryBean` can be an immediate alternative to `LocalContainerEntityManagerFactoryBean` for common JPA purposes: The Hibernate `SessionFactory` will natively expose the JPA `EntityManagerFactory` interface as well, and Hibernate `BeanContainer` integration will be registered out of the box. In combination with `HibernateTransactionManager`, this naturally allows for mixing JPA access code with native Hibernate access code within the same transaction.

NOTE: Hibernate ORM 6.x is officially only supported as a JPA provider. Please use `LocalContainerEntityManagerFactoryBean` with `JpaTransactionManager` there instead.

Since:
  4.2
Author:
  Juergen Hoeller
See Also:
  - `setDataSource(javax.sql.DataSource)`
  - `setPackagesToScan(java.lang.String...)`
  - `HibernateTransactionManager`
  - `LocalSessionFactoryBuilder`
  - `LocalContainerEntityManagerFactoryBean`

## Field Summary

### Fields inherited from interface org.springframework.beans.factory.FactoryBean

`OBJECT_TYPE_ATTRIBUTE`

## Constructor Summary

Constructors
Constructor
Description
`LocalSessionFactoryBean()`

## Method Summary

Modifier and Type
Method
Description
`void`
`afterPropertiesSet()`
`void`
`afterSingletonsInstantiated()`
`protected SessionFactory`
`buildSessionFactory(LocalSessionFactoryBuilder sfb)`
Subclasses can override this method to perform custom initialization of the SessionFactory instance, creating it via the given Configuration object that got prepared by this LocalSessionFactoryBean.
`void`
`destroy()`
`final Configuration`
`getConfiguration()`
Return the Hibernate Configuration object used to build the SessionFactory.
`Properties`
`getHibernateProperties()`
Return the Hibernate properties, if any.
`MetadataSources`
`getMetadataSources()`
Determine the Hibernate `MetadataSources` to use.
`SessionFactory`
`getObject()`
`Class<?>`
`getObjectType()`
`org.springframework.core.io.ResourceLoader`
`getResourceLoader()`
Determine the Spring `ResourceLoader` to use for Hibernate metadata.
`boolean`
`isSingleton()`
`void`
`setAnnotatedClasses(Class<?>... annotatedClasses)`
Specify annotated entity classes to register with this Hibernate SessionFactory.
`void`
`setAnnotatedPackages(String... annotatedPackages)`
Specify the names of annotated packages, for which package-level annotation metadata will be read.
`void`
`setBeanFactory(org.springframework.beans.factory.BeanFactory beanFactory)`
Accept the containing `BeanFactory`, registering corresponding Hibernate `BeanContainer` integration for it if possible.
`void`
`setBootstrapExecutor(org.springframework.core.task.AsyncTaskExecutor bootstrapExecutor)`
Specify an asynchronous executor for background bootstrapping, for example, a `SimpleAsyncTaskExecutor`.
`void`
`setCacheableMappingLocations(org.springframework.core.io.Resource... cacheableMappingLocations)`
Set locations of cacheable Hibernate mapping files, for example as web app resource "/WEB-INF/mapping/example.hbm.xml".
`void`
`setCacheRegionFactory(RegionFactory cacheRegionFactory)`
Set the Hibernate `RegionFactory` to use for the SessionFactory.
`void`
`setConfigLocation(org.springframework.core.io.Resource configLocation)`
Set the location of a single Hibernate XML config file, for example as classpath resource "classpath:hibernate.cfg.xml".
`void`
`setConfigLocations(org.springframework.core.io.Resource... configLocations)`
Set the locations of multiple Hibernate XML config files, for example as classpath resources "classpath:hibernate.cfg.xml,classpath:extension.cfg.xml".
`void`
`setCurrentTenantIdentifierResolver(CurrentTenantIdentifierResolver currentTenantIdentifierResolver)`
Set a `CurrentTenantIdentifierResolver` to be passed on to the SessionFactory.
`void`
`setDataSource(DataSource dataSource)`
Set the DataSource to be used by the SessionFactory.
`void`
`setEntityInterceptor(Interceptor entityInterceptor)`
Set a Hibernate entity interceptor that allows to inspect and change property values before writing to and reading from the database.
`void`
`setEntityTypeFilters(org.springframework.core.type.filter.TypeFilter... entityTypeFilters)`
Specify custom type filters for Spring-based scanning for entity classes.
`void`
`setHibernateIntegrators(Integrator... hibernateIntegrators)`
Specify one or more Hibernate `Integrator` implementations to apply.
`void`
`setHibernateProperties(Properties hibernateProperties)`
Set Hibernate properties, such as "hibernate.dialect".
`void`
`setImplicitNamingStrategy(ImplicitNamingStrategy implicitNamingStrategy)`
Set a Hibernate 5 `ImplicitNamingStrategy` for the SessionFactory.
`void`
`setJtaTransactionManager(Object jtaTransactionManager)`
Set the Spring `JtaTransactionManager` or the JTA `TransactionManager` to be used with Hibernate, if any.
`void`
`setMappingDirectoryLocations(org.springframework.core.io.Resource... mappingDirectoryLocations)`
Set locations of directories that contain Hibernate mapping resources, like "WEB-INF/mappings".
`void`
`setMappingJarLocations(org.springframework.core.io.Resource... mappingJarLocations)`
Set locations of jar files that contain Hibernate mapping resources, like "WEB-INF/lib/example.hbm.jar".
`void`
`setMappingLocations(org.springframework.core.io.Resource... mappingLocations)`
Set locations of Hibernate mapping files, for example as classpath resource "classpath:example.hbm.xml".
`void`
`setMappingResources(String... mappingResources)`
Set Hibernate mapping resources to be found in the class path, like "example.hbm.xml" or "mypackage/example.hbm.xml".
`void`
`setMetadataSources(MetadataSources metadataSources)`
Specify a Hibernate `MetadataSources` service to use (for example, reusing an existing one), potentially populated with a custom Hibernate bootstrap `ServiceRegistry` as well.
`void`
`setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider)`
Set a `MultiTenantConnectionProvider` to be passed on to the SessionFactory.
`void`
`setPackagesToScan(String... packagesToScan)`
Specify packages to search for autodetection of your entity classes in the classpath.
`void`
`setPhysicalNamingStrategy(PhysicalNamingStrategy physicalNamingStrategy)`
Set a Hibernate 5 `PhysicalNamingStrategy` for the SessionFactory.
`void`
`setResourceLoader(org.springframework.core.io.ResourceLoader resourceLoader)`
Specify a Spring `ResourceLoader` to use for Hibernate metadata.

### Methods inherited from class org.springframework.orm.hibernate5.HibernateExceptionTranslator

`convertHibernateAccessException, setJdbcExceptionTranslator, translateExceptionIfPossible`

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

## Constructor Details

### LocalSessionFactoryBean

public LocalSessionFactoryBean()

## Method Details

### setDataSource

public void setDataSource(DataSource dataSource)
Set the DataSource to be used by the SessionFactory. If set, this will override corresponding settings in Hibernate properties.

If this is set, the Hibernate settings should not define a connection provider to avoid meaningless double configuration.

### setConfigLocation

public void setConfigLocation(org.springframework.core.io.Resource configLocation)
Set the location of a single Hibernate XML config file, for example as classpath resource "classpath:hibernate.cfg.xml".

Note: Can be omitted when all necessary properties and mapping resources are specified locally via this bean.

See Also:
  - `Configuration.configure(java.net.URL)`

### setConfigLocations

public void setConfigLocations(org.springframework.core.io.Resource... configLocations)
Set the locations of multiple Hibernate XML config files, for example as classpath resources "classpath:hibernate.cfg.xml,classpath:extension.cfg.xml".

Note: Can be omitted when all necessary properties and mapping resources are specified locally via this bean.

See Also:
  - `Configuration.configure(java.net.URL)`

### setMappingResources

public void setMappingResources(String... mappingResources)
Set Hibernate mapping resources to be found in the class path, like "example.hbm.xml" or "mypackage/example.hbm.xml". Analogous to mapping entries in a Hibernate XML config file. Alternative to the more generic setMappingLocations method.

Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.

See Also:
  - `setMappingLocations(org.springframework.core.io.Resource...)`
  - `Configuration.addResource(java.lang.String, java.lang.ClassLoader)`

### setMappingLocations

public void setMappingLocations(org.springframework.core.io.Resource... mappingLocations)
Set locations of Hibernate mapping files, for example as classpath resource "classpath:example.hbm.xml". Supports any resource location via Spring's resource abstraction, for example relative paths like "WEB-INF/mappings/example.hbm.xml" when running in an application context.

Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.

See Also:
  - `Configuration.addInputStream(java.io.InputStream)`

### setCacheableMappingLocations

public void setCacheableMappingLocations(org.springframework.core.io.Resource... cacheableMappingLocations)
Set locations of cacheable Hibernate mapping files, for example as web app resource "/WEB-INF/mapping/example.hbm.xml". Supports any resource location via Spring's resource abstraction, as long as the resource can be resolved in the file system.

Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.

See Also:
  - `Configuration.addCacheableFile(File)`

### setMappingJarLocations

public void setMappingJarLocations(org.springframework.core.io.Resource... mappingJarLocations)
Set locations of jar files that contain Hibernate mapping resources, like "WEB-INF/lib/example.hbm.jar".

Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.

See Also:
  - `Configuration.addJar(File)`

### setMappingDirectoryLocations

public void setMappingDirectoryLocations(org.springframework.core.io.Resource... mappingDirectoryLocations)
Set locations of directories that contain Hibernate mapping resources, like "WEB-INF/mappings".

Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.

See Also:
  - `Configuration.addDirectory(File)`

### setEntityInterceptor

public void setEntityInterceptor(Interceptor entityInterceptor)
Set a Hibernate entity interceptor that allows to inspect and change property values before writing to and reading from the database. Will get applied to any new Session created by this factory.

See Also:
  - `Configuration.setInterceptor(org.hibernate.Interceptor)`

### setImplicitNamingStrategy

public void setImplicitNamingStrategy(ImplicitNamingStrategy implicitNamingStrategy)
Set a Hibernate 5 `ImplicitNamingStrategy` for the SessionFactory.

See Also:
  - `Configuration.setImplicitNamingStrategy(org.hibernate.boot.model.naming.ImplicitNamingStrategy)`

### setPhysicalNamingStrategy

public void setPhysicalNamingStrategy(PhysicalNamingStrategy physicalNamingStrategy)
Set a Hibernate 5 `PhysicalNamingStrategy` for the SessionFactory.

See Also:
  - `Configuration.setPhysicalNamingStrategy(org.hibernate.boot.model.naming.PhysicalNamingStrategy)`

### setJtaTransactionManager

public void setJtaTransactionManager(Object jtaTransactionManager)
Set the Spring `JtaTransactionManager` or the JTA `TransactionManager` to be used with Hibernate, if any. Implicitly sets up `JtaPlatform`.

See Also:
  - `LocalSessionFactoryBuilder.setJtaTransactionManager(java.lang.Object)`

### setCacheRegionFactory

public void setCacheRegionFactory(RegionFactory cacheRegionFactory)
Set the Hibernate `RegionFactory` to use for the SessionFactory. Allows for using a Spring-managed `RegionFactory` instance.

Note: If this is set, the Hibernate settings should not define a cache provider to avoid meaningless double configuration.

Since:
  5.1
See Also:
  - `LocalSessionFactoryBuilder.setCacheRegionFactory(org.hibernate.cache.spi.RegionFactory)`

### setMultiTenantConnectionProvider

public void setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider)
Set a `MultiTenantConnectionProvider` to be passed on to the SessionFactory.

Since:
  4.3
See Also:
  - `LocalSessionFactoryBuilder.setMultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider)`

### setCurrentTenantIdentifierResolver

public void setCurrentTenantIdentifierResolver(CurrentTenantIdentifierResolver currentTenantIdentifierResolver)
Set a `CurrentTenantIdentifierResolver` to be passed on to the SessionFactory.

See Also:
  - `LocalSessionFactoryBuilder.setCurrentTenantIdentifierResolver(org.hibernate.context.spi.CurrentTenantIdentifierResolver)`

### setHibernateProperties

public void setHibernateProperties(Properties hibernateProperties)
Set Hibernate properties, such as "hibernate.dialect".

Note: Do not specify a transaction provider here when using Spring-driven transactions. It is also advisable to omit connection provider settings and use a Spring-set DataSource instead.

See Also:
  - `setDataSource(javax.sql.DataSource)`

### getHibernateProperties

public Properties getHibernateProperties()
Return the Hibernate properties, if any. Mainly available for configuration through property paths that specify individual keys.

### setEntityTypeFilters

public void setEntityTypeFilters(org.springframework.core.type.filter.TypeFilter... entityTypeFilters)
Specify custom type filters for Spring-based scanning for entity classes.

Default is to search all specified packages for classes annotated with `@jakarta.persistence.Entity`, `@jakarta.persistence.Embeddable` or `@jakarta.persistence.MappedSuperclass`.

See Also:
  - `setPackagesToScan(java.lang.String...)`

### setAnnotatedClasses

public void setAnnotatedClasses(Class<?>... annotatedClasses)
Specify annotated entity classes to register with this Hibernate SessionFactory.

See Also:
  - `Configuration.addAnnotatedClass(Class)`

### setAnnotatedPackages

public void setAnnotatedPackages(String... annotatedPackages)
Specify the names of annotated packages, for which package-level annotation metadata will be read.

See Also:
  - `Configuration.addPackage(String)`

### setPackagesToScan

public void setPackagesToScan(String... packagesToScan)
Specify packages to search for autodetection of your entity classes in the classpath. This is analogous to Spring's component-scan feature (`ClassPathBeanDefinitionScanner`).

### setBootstrapExecutor

public void setBootstrapExecutor(org.springframework.core.task.AsyncTaskExecutor bootstrapExecutor)
Specify an asynchronous executor for background bootstrapping, for example, a `SimpleAsyncTaskExecutor`.

`SessionFactory` initialization will then switch into background bootstrap mode, with a `SessionFactory` proxy immediately returned for injection purposes instead of waiting for Hibernate's bootstrapping to complete. However, note that the first actual call to a `SessionFactory` method will then block until Hibernate's bootstrapping completed, if not ready by then. For maximum benefit, make sure to avoid early `SessionFactory` calls in init methods of related beans, even for metadata introspection purposes.

As of 6.2, Hibernate initialization is enforced before context refresh completion, waiting for asynchronous bootstrapping to complete by then.

Since:
  4.3
See Also:
  - `LocalSessionFactoryBuilder.buildSessionFactory(AsyncTaskExecutor)`

### setHibernateIntegrators

public void setHibernateIntegrators(Integrator... hibernateIntegrators)
Specify one or more Hibernate `Integrator` implementations to apply.

This will only be applied for an internally built `MetadataSources` instance. `setMetadataSources(org.hibernate.boot.MetadataSources)` effectively overrides such settings, with integrators to be applied to the externally built `MetadataSources`.

Since:
  5.1
See Also:
  - `setMetadataSources(org.hibernate.boot.MetadataSources)`
  - `BootstrapServiceRegistryBuilder.applyIntegrator(org.hibernate.integrator.spi.Integrator)`

### setMetadataSources

public void setMetadataSources(MetadataSources metadataSources)
Specify a Hibernate `MetadataSources` service to use (for example, reusing an existing one), potentially populated with a custom Hibernate bootstrap `ServiceRegistry` as well.

Since:
  4.3
See Also:
  - `MetadataSources(ServiceRegistry)`
  - `BootstrapServiceRegistryBuilder.build()`

### getMetadataSources

public MetadataSources getMetadataSources()
Determine the Hibernate `MetadataSources` to use.

Can also be externally called to initialize and pre-populate a `MetadataSources` instance which is then going to be used for `SessionFactory` building.

Returns:
  the MetadataSources to use (never `null`)
Since:
  4.3
See Also:
  - `LocalSessionFactoryBuilder(DataSource, ResourceLoader, MetadataSources)`

### setResourceLoader

public void setResourceLoader(org.springframework.core.io.ResourceLoader resourceLoader)
Specify a Spring `ResourceLoader` to use for Hibernate metadata.

Specified by:
  `setResourceLoader` in interface `org.springframework.context.ResourceLoaderAware`
Parameters:
  `resourceLoader` - the ResourceLoader to use (never `null`)

### getResourceLoader

public org.springframework.core.io.ResourceLoader getResourceLoader()
Determine the Spring `ResourceLoader` to use for Hibernate metadata.

Returns:
  the ResourceLoader to use (never `null`)
Since:
  4.3

### setBeanFactory

public void setBeanFactory(org.springframework.beans.factory.BeanFactory beanFactory)
Accept the containing `BeanFactory`, registering corresponding Hibernate `BeanContainer` integration for it if possible. This requires a Spring `ConfigurableListableBeanFactory`.

Specified by:
  `setBeanFactory` in interface `org.springframework.beans.factory.BeanFactoryAware`
Since:
  5.1
See Also:
  - `SpringBeanContainer`
  - `LocalSessionFactoryBuilder.setBeanContainer(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)`

### afterPropertiesSet

public void afterPropertiesSet() throws IOException

Specified by:
  `afterPropertiesSet` in interface `org.springframework.beans.factory.InitializingBean`
Throws:
  `IOException`

### afterSingletonsInstantiated

public void afterSingletonsInstantiated()

Specified by:
  `afterSingletonsInstantiated` in interface `org.springframework.beans.factory.SmartInitializingSingleton`

### buildSessionFactory

protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb)
Subclasses can override this method to perform custom initialization of the SessionFactory instance, creating it via the given Configuration object that got prepared by this LocalSessionFactoryBean.

The default implementation invokes LocalSessionFactoryBuilder's buildSessionFactory. A custom implementation could prepare the instance in a specific way (for example, applying a custom ServiceRegistry) or use a custom SessionFactoryImpl subclass.

Parameters:
  `sfb` - a LocalSessionFactoryBuilder prepared by this LocalSessionFactoryBean
Returns:
  the SessionFactory instance
See Also:
  - `LocalSessionFactoryBuilder.buildSessionFactory(org.springframework.core.task.AsyncTaskExecutor)`

### getConfiguration

public final Configuration getConfiguration()
Return the Hibernate Configuration object used to build the SessionFactory. Allows for access to configuration metadata stored there (rarely needed).

Throws:
  `IllegalStateException` - if the Configuration object has not been initialized yet

### getObject

@Nullable public SessionFactory getObject()

Specified by:
  `getObject` in interface `org.springframework.beans.factory.FactoryBean<SessionFactory>`

### getObjectType

public Class<?> getObjectType()

Specified by:
  `getObjectType` in interface `org.springframework.beans.factory.FactoryBean<SessionFactory>`

### isSingleton

public boolean isSingleton()

Specified by:
  `isSingleton` in interface `org.springframework.beans.factory.FactoryBean<SessionFactory>`

### destroy

public void destroy()

Specified by:
  `destroy` in interface `org.springframework.beans.factory.DisposableBean`