Class LocalSessionFactoryBean
- java.lang.Object
- org.springframework.orm.hibernate5.HibernateExceptionTranslator
- org.springframework.orm.hibernate5.LocalSessionFactoryBean
- All Implemented Interfaces:
Aware,DisposableBean,FactoryBean<SessionFactory>,InitializingBean,ResourceLoaderAware,PersistenceExceptionTranslator
public class LocalSessionFactoryBean extends HibernateExceptionTranslator implements FactoryBean<SessionFactory>, ResourceLoaderAware, InitializingBean, DisposableBean
FactoryBeanthat creates a HibernateSessionFactory. This is the usual way to set up a shared Hibernate SessionFactory in a Spring application context; the SessionFactory can then be passed to Hibernate-based data access objects via dependency injection.Compatible with Hibernate 5.0/5.1 as well as 5.2, as of Spring 4.3.
- Since:
- 4.2
- Author:
- Juergen Hoeller
- See Also:
setDataSource(javax.sql.DataSource),setPackagesToScan(java.lang.String...),LocalSessionFactoryBuilder
Constructor Summary
Constructors Constructor Description LocalSessionFactoryBean()
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidafterPropertiesSet()Invoked by the containingBeanFactoryafter it has set all bean properties and satisfiedBeanFactoryAware,ApplicationContextAwareetc.protected SessionFactorybuildSessionFactory(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.voiddestroy()Invoked by the containingBeanFactoryon destruction of a bean.ConfigurationgetConfiguration()Return the Hibernate Configuration object used to build the SessionFactory.PropertiesgetHibernateProperties()Return the Hibernate properties, if any.org.hibernate.boot.MetadataSourcesgetMetadataSources()Determine the HibernateMetadataSourcesto use.SessionFactorygetObject()Return an instance (possibly shared or independent) of the object managed by this factory.Class<?>getObjectType()Return the type of object that this FactoryBean creates, ornullif not known in advance.ResourceLoadergetResourceLoader()Determine the SpringResourceLoaderto use for Hibernate metadata.booleanisSingleton()Is the object managed by this factory a singleton? That is, willFactoryBean.getObject()always return the same object (a reference that can be cached)?voidsetAnnotatedClasses(Class<?>... annotatedClasses)Specify annotated entity classes to register with this Hibernate SessionFactory.voidsetAnnotatedPackages(String... annotatedPackages)Specify the names of annotated packages, for which package-level annotation metadata will be read.voidsetBootstrapExecutor(AsyncTaskExecutor bootstrapExecutor)Specify an asynchronous executor for background bootstrapping, e.g.voidsetCacheableMappingLocations(Resource... cacheableMappingLocations)Set locations of cacheable Hibernate mapping files, for example as web app resource "/WEB-INF/mapping/example.hbm.xml".voidsetConfigLocation(Resource configLocation)Set the location of a single Hibernate XML config file, for example as classpath resource "classpath:hibernate.cfg.xml".voidsetConfigLocations(Resource... configLocations)Set the locations of multiple Hibernate XML config files, for example as classpath resources "classpath:hibernate.cfg.xml,classpath:extension.cfg.xml".voidsetCurrentTenantIdentifierResolver(CurrentTenantIdentifierResolver currentTenantIdentifierResolver)Set aCurrentTenantIdentifierResolverto be passed on to the SessionFactory.voidsetDataSource(DataSource dataSource)Set the DataSource to be used by the SessionFactory.voidsetEntityInterceptor(Interceptor entityInterceptor)Set a Hibernate entity interceptor that allows to inspect and change property values before writing to and reading from the database.voidsetEntityTypeFilters(TypeFilter... entityTypeFilters)Specify custom type filters for Spring-based scanning for entity classes.voidsetHibernateProperties(Properties hibernateProperties)Set Hibernate properties, such as "hibernate.dialect".voidsetImplicitNamingStrategy(org.hibernate.boot.model.naming.ImplicitNamingStrategy implicitNamingStrategy)Set a Hibernate 5.0 ImplicitNamingStrategy for the SessionFactory.voidsetJtaTransactionManager(Object jtaTransactionManager)Set the SpringJtaTransactionManageror the JTATransactionManagerto be used with Hibernate, if any.voidsetMappingDirectoryLocations(Resource... mappingDirectoryLocations)Set locations of directories that contain Hibernate mapping resources, like "WEB-INF/mappings".voidsetMappingJarLocations(Resource... mappingJarLocations)Set locations of jar files that contain Hibernate mapping resources, like "WEB-INF/lib/example.hbm.jar".voidsetMappingLocations(Resource... mappingLocations)Set locations of Hibernate mapping files, for example as classpath resource "classpath:example.hbm.xml".voidsetMappingResources(String... mappingResources)Set Hibernate mapping resources to be found in the class path, like "example.hbm.xml" or "mypackage/example.hbm.xml".voidsetMetadataSources(org.hibernate.boot.MetadataSources metadataSources)Specify a HibernateMetadataSourcesservice to use (e.g.voidsetMultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider multiTenantConnectionProvider)Set aMultiTenantConnectionProviderto be passed on to the SessionFactory.voidsetPackagesToScan(String... packagesToScan)Specify packages to search for autodetection of your entity classes in the classpath.voidsetPhysicalNamingStrategy(org.hibernate.boot.model.naming.PhysicalNamingStrategy physicalNamingStrategy)Set a Hibernate 5.0 PhysicalNamingStrategy for the SessionFactory.voidsetResourceLoader(ResourceLoader resourceLoader)Specify a SpringResourceLoaderto use for Hibernate metadata.Methods inherited from class org.springframework.orm.hibernate5.HibernateExceptionTranslator
convertHibernateAccessException, translateExceptionIfPossible
Constructor Detail
LocalSessionFactoryBean
public LocalSessionFactoryBean()
Method Detail
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(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.
setConfigLocations
public void setConfigLocations(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.
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.
setMappingLocations
public void setMappingLocations(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.
setCacheableMappingLocations
public void setCacheableMappingLocations(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(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(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.
setImplicitNamingStrategy
public void setImplicitNamingStrategy(org.hibernate.boot.model.naming.ImplicitNamingStrategy implicitNamingStrategy)
Set a Hibernate 5.0 ImplicitNamingStrategy for the SessionFactory.- See Also:
Configuration#setImplicitNamingStrategy
setPhysicalNamingStrategy
public void setPhysicalNamingStrategy(org.hibernate.boot.model.naming.PhysicalNamingStrategy physicalNamingStrategy)
Set a Hibernate 5.0 PhysicalNamingStrategy for the SessionFactory.- See Also:
Configuration#setPhysicalNamingStrategy
setJtaTransactionManager
public void setJtaTransactionManager(Object jtaTransactionManager)
Set the SpringJtaTransactionManageror the JTATransactionManagerto be used with Hibernate, if any. Implicitly sets upJtaPlatform.
setMultiTenantConnectionProvider
public void setMultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider multiTenantConnectionProvider)
Set aMultiTenantConnectionProviderto be passed on to the SessionFactory.
setCurrentTenantIdentifierResolver
public void setCurrentTenantIdentifierResolver(CurrentTenantIdentifierResolver currentTenantIdentifierResolver)
Set aCurrentTenantIdentifierResolverto be passed on to the SessionFactory.
setEntityTypeFilters
public void setEntityTypeFilters(TypeFilter... entityTypeFilters)
Specify custom type filters for Spring-based scanning for entity classes.Default is to search all specified packages for classes annotated with
@javax.persistence.Entity,@javax.persistence.Embeddableor@javax.persistence.MappedSuperclass.
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.
setAnnotatedClasses
public void setAnnotatedClasses(Class<?>... annotatedClasses)
Specify annotated entity classes to register with this Hibernate SessionFactory.
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(AsyncTaskExecutor bootstrapExecutor)
Specify an asynchronous executor for background bootstrapping, e.g. aSimpleAsyncTaskExecutor.SessionFactoryinitialization will then switch into background bootstrap mode, with aSessionFactoryproxy immediately returned for injection purposes instead of waiting for Hibernate's bootstrapping to complete. However, note that the first actual call to aSessionFactorymethod will then block until Hibernate's bootstrapping completed, if not ready by then. For maximum benefit, make sure to avoid earlySessionFactorycalls in init methods of related beans, even for metadata introspection purposes.- Since:
- 4.3
- See Also:
LocalSessionFactoryBuilder.buildSessionFactory(AsyncTaskExecutor)
setMetadataSources
public void setMetadataSources(org.hibernate.boot.MetadataSources metadataSources)
Specify a HibernateMetadataSourcesservice to use (e.g. reusing an existing one), potentially populated with a custom Hibernate bootstrapServiceRegistryas well.- Since:
- 4.3
getMetadataSources
public org.hibernate.boot.MetadataSources getMetadataSources()
Determine the HibernateMetadataSourcesto use.Can also be externally called to initialize and pre-populate a
MetadataSourcesinstance which is then going to be used forSessionFactorybuilding.- Returns:
- the MetadataSources to use (never
null) - Since:
- 4.3
- See Also:
LocalSessionFactoryBuilder(DataSource, ResourceLoader, MetadataSources)
setResourceLoader
public void setResourceLoader(ResourceLoader resourceLoader)
Specify a SpringResourceLoaderto use for Hibernate metadata.- Specified by:
setResourceLoaderin interfaceResourceLoaderAware- Parameters:
resourceLoader- the ResourceLoader to use (nevernull)- See Also:
ResourcePatternResolver,ResourcePatternUtils.getResourcePatternResolver(org.springframework.core.io.ResourceLoader)
getResourceLoader
public ResourceLoader getResourceLoader()
Determine the SpringResourceLoaderto use for Hibernate metadata.- Returns:
- the ResourceLoader to use (never
null) - Since:
- 4.3
afterPropertiesSet
public void afterPropertiesSet() throws IOException
Description copied from interface:InitializingBeanInvoked by the containingBeanFactoryafter it has set all bean properties and satisfiedBeanFactoryAware,ApplicationContextAwareetc.This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.
- Specified by:
afterPropertiesSetin interfaceInitializingBean- Throws:
IOException
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 (e.g. applying a custom ServiceRegistry) or use a custom SessionFactoryImpl subclass.
- Parameters:
sfb- 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
public SessionFactory getObject()
Description copied from interface:FactoryBeanReturn an instance (possibly shared or independent) of the object managed by this factory.As with a
BeanFactory, this allows support for both the Singleton and Prototype design pattern.If this FactoryBean is not fully initialized yet at the time of the call (for example because it is involved in a circular reference), throw a corresponding
FactoryBeanNotInitializedException.As of Spring 2.0, FactoryBeans are allowed to return
nullobjects. The factory will consider this as normal value to be used; it will not throw a FactoryBeanNotInitializedException in this case anymore. FactoryBean implementations are encouraged to throw FactoryBeanNotInitializedException themselves now, as appropriate.- Specified by:
getObjectin interfaceFactoryBean<SessionFactory>- Returns:
- an instance of the bean (can be
null) - See Also:
FactoryBeanNotInitializedException
getObjectType
public Class<?> getObjectType()
Description copied from interface:FactoryBeanReturn the type of object that this FactoryBean creates, ornullif not known in advance.This allows one to check for specific types of beans without instantiating objects, for example on autowiring.
In the case of implementations that are creating a singleton object, this method should try to avoid singleton creation as far as possible; it should rather estimate the type in advance. For prototypes, returning a meaningful type here is advisable too.
This method can be called before this FactoryBean has been fully initialized. It must not rely on state created during initialization; of course, it can still use such state if available.
NOTE: Autowiring will simply ignore FactoryBeans that return
nullhere. Therefore it is highly recommended to implement this method properly, using the current state of the FactoryBean.- Specified by:
getObjectTypein interfaceFactoryBean<SessionFactory>- Returns:
- the type of object that this FactoryBean creates, or
nullif not known at the time of the call - See Also:
ListableBeanFactory.getBeansOfType(java.lang.Class<T>)
isSingleton
public boolean isSingleton()
Description copied from interface:FactoryBeanIs the object managed by this factory a singleton? That is, willFactoryBean.getObject()always return the same object (a reference that can be cached)?NOTE: If a FactoryBean indicates to hold a singleton object, the object returned from
getObject()might get cached by the owning BeanFactory. Hence, do not returntrueunless the FactoryBean always exposes the same reference.The singleton status of the FactoryBean itself will generally be provided by the owning BeanFactory; usually, it has to be defined as singleton there.
NOTE: This method returning
falsedoes not necessarily indicate that returned objects are independent instances. An implementation of the extendedSmartFactoryBeaninterface may explicitly indicate independent instances through itsSmartFactoryBean.isPrototype()method. PlainFactoryBeanimplementations which do not implement this extended interface are simply assumed to always return independent instances if theisSingleton()implementation returnsfalse.- Specified by:
isSingletonin interfaceFactoryBean<SessionFactory>- Returns:
- whether the exposed object is a singleton
- See Also:
FactoryBean.getObject(),SmartFactoryBean.isPrototype()
destroy
public void destroy()
Description copied from interface:DisposableBeanInvoked by the containingBeanFactoryon destruction of a bean.- Specified by:
destroyin interfaceDisposableBean