类 LocalSessionFactoryBean
- java.lang.Object
- org.springframework.orm.hibernate5.HibernateExceptionTranslator
- org.springframework.orm.hibernate5.LocalSessionFactoryBean
- 所有已实现的接口:
Aware
,BeanFactoryAware
,DisposableBean
,FactoryBean<SessionFactory>
,InitializingBean
,ResourceLoaderAware
,PersistenceExceptionTranslator
public class LocalSessionFactoryBean extends HibernateExceptionTranslator implements FactoryBean<SessionFactory>, ResourceLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean
FactoryBean
that 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 data access objects via dependency injection.Compatible with Hibernate 5.0/5.1 as well as 5.2/5.3/5.4, as of Spring 5.2. Set up with Hibernate 5.2+,
LocalSessionFactoryBean
is an immediate alternative toLocalContainerEntityManagerFactoryBean
for common JPA purposes: In particular with Hibernate 5.3/5.4, the HibernateSessionFactory
will natively expose the JPAEntityManagerFactory
interface as well, and HibernateBeanContainer
integration will be registered out of the box. In combination withHibernateTransactionManager
, this naturally allows for mixing JPA access code with native Hibernate access code within the same transaction.- 从以下版本开始:
- 4.2
- 作者:
- Juergen Hoeller
- 另请参阅:
setDataSource(javax.sql.DataSource)
,setPackagesToScan(java.lang.String...)
,HibernateTransactionManager
,LocalSessionFactoryBuilder
,LocalContainerEntityManagerFactoryBean
字段概要
从接口继承的字段 org.springframework.beans.factory.FactoryBean
OBJECT_TYPE_ATTRIBUTE
构造器概要
构造器 构造器 说明 LocalSessionFactoryBean()
方法概要
所有方法 实例方法 具体方法 修饰符和类型 方法 说明 void
afterPropertiesSet()
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,ApplicationContextAware
etc.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()
Invoked by the containingBeanFactory
on destruction of a bean.Configuration
getConfiguration()
Return the Hibernate Configuration object used to build the SessionFactory.Properties
getHibernateProperties()
Return the Hibernate properties, if any.org.hibernate.boot.MetadataSources
getMetadataSources()
Determine the HibernateMetadataSources
to use.SessionFactory
getObject()
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, ornull
if not known in advance.ResourceLoader
getResourceLoader()
Determine the SpringResourceLoader
to use for Hibernate metadata.boolean
isSingleton()
Is the object managed by this factory a singleton?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(BeanFactory beanFactory)
Accept the containingBeanFactory
, registering corresponding HibernateBeanContainer
integration for it if possible.void
setBootstrapExecutor(AsyncTaskExecutor bootstrapExecutor)
Specify an asynchronous executor for background bootstrapping, e.g. aSimpleAsyncTaskExecutor
.void
setCacheableMappingLocations(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 HibernateRegionFactory
to use for the SessionFactory.void
setConfigLocation(Resource configLocation)
Set the location of a single Hibernate XML config file, for example as classpath resource "classpath:hibernate.cfg.xml".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".void
setCurrentTenantIdentifierResolver(CurrentTenantIdentifierResolver currentTenantIdentifierResolver)
Set aCurrentTenantIdentifierResolver
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(TypeFilter... entityTypeFilters)
Specify custom type filters for Spring-based scanning for entity classes.void
setHibernateIntegrators(Integrator... hibernateIntegrators)
Specify one or more HibernateIntegrator
implementations to apply.void
setHibernateProperties(Properties hibernateProperties)
Set Hibernate properties, such as "hibernate.dialect".void
setImplicitNamingStrategy(org.hibernate.boot.model.naming.ImplicitNamingStrategy implicitNamingStrategy)
Set a Hibernate 5ImplicitNamingStrategy
for the SessionFactory.void
setJtaTransactionManager(Object jtaTransactionManager)
Set the SpringJtaTransactionManager
or the JTATransactionManager
to be used with Hibernate, if any.void
setMappingDirectoryLocations(Resource... mappingDirectoryLocations)
Set locations of directories that contain Hibernate mapping resources, like "WEB-INF/mappings".void
setMappingJarLocations(Resource... mappingJarLocations)
Set locations of jar files that contain Hibernate mapping resources, like "WEB-INF/lib/example.hbm.jar".void
setMappingLocations(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(org.hibernate.boot.MetadataSources metadataSources)
Specify a HibernateMetadataSources
service to use (e.g. reusing an existing one), potentially populated with a custom Hibernate bootstrapServiceRegistry
as well.void
setMultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider multiTenantConnectionProvider)
Set aMultiTenantConnectionProvider
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(org.hibernate.boot.model.naming.PhysicalNamingStrategy physicalNamingStrategy)
Set a Hibernate 5PhysicalNamingStrategy
for the SessionFactory.void
setResourceLoader(ResourceLoader resourceLoader)
Specify a SpringResourceLoader
to use for Hibernate metadata.从类继承的方法 org.springframework.orm.hibernate5.HibernateExceptionTranslator
convertHibernateAccessException, setJdbcExceptionTranslator, translateExceptionIfPossible
构造器详细资料
LocalSessionFactoryBean
public LocalSessionFactoryBean()
方法详细资料
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.
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.
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.
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 5ImplicitNamingStrategy
for the SessionFactory.
setPhysicalNamingStrategy
public void setPhysicalNamingStrategy(org.hibernate.boot.model.naming.PhysicalNamingStrategy physicalNamingStrategy)
Set a Hibernate 5PhysicalNamingStrategy
for the SessionFactory.
setJtaTransactionManager
public void setJtaTransactionManager(Object jtaTransactionManager)
Set the SpringJtaTransactionManager
or the JTATransactionManager
to be used with Hibernate, if any. Implicitly sets upJtaPlatform
.
setCacheRegionFactory
public void setCacheRegionFactory(RegionFactory cacheRegionFactory)
Set the HibernateRegionFactory
to use for the SessionFactory. Allows for using a Spring-managedRegionFactory
instance.Note: If this is set, the Hibernate settings should not define a cache provider to avoid meaningless double configuration.
setMultiTenantConnectionProvider
public void setMultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider multiTenantConnectionProvider)
Set aMultiTenantConnectionProvider
to be passed on to the SessionFactory.
setCurrentTenantIdentifierResolver
public void setCurrentTenantIdentifierResolver(CurrentTenantIdentifierResolver currentTenantIdentifierResolver)
Set aCurrentTenantIdentifierResolver
to be passed on to the SessionFactory.
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.
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(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.Embeddable
or@javax.persistence.MappedSuperclass
.
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.
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
.SessionFactory
initialization will then switch into background bootstrap mode, with aSessionFactory
proxy immediately returned for injection purposes instead of waiting for Hibernate's bootstrapping to complete. However, note that the first actual call to aSessionFactory
method will then block until Hibernate's bootstrapping completed, if not ready by then. For maximum benefit, make sure to avoid earlySessionFactory
calls in init methods of related beans, even for metadata introspection purposes.
setHibernateIntegrators
public void setHibernateIntegrators(Integrator... hibernateIntegrators)
Specify one or more HibernateIntegrator
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 builtMetadataSources
.- 从以下版本开始:
- 5.1
- 另请参阅:
setMetadataSources(org.hibernate.boot.MetadataSources)
,BootstrapServiceRegistryBuilder.applyIntegrator(org.hibernate.integrator.spi.Integrator)
setMetadataSources
public void setMetadataSources(org.hibernate.boot.MetadataSources metadataSources)
Specify a HibernateMetadataSources
service to use (e.g. reusing an existing one), potentially populated with a custom Hibernate bootstrapServiceRegistry
as well.- 从以下版本开始:
- 4.3
- 另请参阅:
MetadataSources(ServiceRegistry)
,BootstrapServiceRegistryBuilder.build()
getMetadataSources
public org.hibernate.boot.MetadataSources getMetadataSources()
Determine the HibernateMetadataSources
to use.Can also be externally called to initialize and pre-populate a
MetadataSources
instance which is then going to be used forSessionFactory
building.- 返回:
- the MetadataSources to use (never
null
) - 从以下版本开始:
- 4.3
- 另请参阅:
LocalSessionFactoryBuilder(DataSource, ResourceLoader, MetadataSources)
setResourceLoader
public void setResourceLoader(ResourceLoader resourceLoader)
Specify a SpringResourceLoader
to use for Hibernate metadata.- 指定者:
setResourceLoader
在接口中ResourceLoaderAware
- 参数:
resourceLoader
- the ResourceLoader to use (nevernull
)- 另请参阅:
ResourcePatternResolver
,ResourcePatternUtils.getResourcePatternResolver(org.springframework.core.io.ResourceLoader)
getResourceLoader
public ResourceLoader getResourceLoader()
Determine the SpringResourceLoader
to use for Hibernate metadata.- 返回:
- the ResourceLoader to use (never
null
) - 从以下版本开始:
- 4.3
setBeanFactory
public void setBeanFactory(BeanFactory beanFactory)
Accept the containingBeanFactory
, registering corresponding HibernateBeanContainer
integration for it if possible. This requires a SpringConfigurableListableBeanFactory
and Hibernate 5.3 or higher on the classpath.- 指定者:
setBeanFactory
在接口中BeanFactoryAware
- 参数:
beanFactory
- owning BeanFactory (nevernull
). The bean can immediately call methods on the factory.- 从以下版本开始:
- 5.1
- 另请参阅:
SpringBeanContainer
,LocalSessionFactoryBuilder.setBeanContainer(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)
afterPropertiesSet
public void afterPropertiesSet() throws IOException
从接口复制的说明:InitializingBean
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,ApplicationContextAware
etc.This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.
- 指定者:
afterPropertiesSet
在接口中InitializingBean
- 抛出:
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.
- 参数:
sfb
- a LocalSessionFactoryBuilder prepared by this LocalSessionFactoryBean- 返回:
- the SessionFactory instance
- 另请参阅:
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).- 抛出:
IllegalStateException
- if the Configuration object has not been initialized yet
getObject
@Nullable public SessionFactory getObject()
从接口复制的说明:FactoryBean
Return 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
null
objects. 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.- 指定者:
getObject
在接口中FactoryBean<SessionFactory>
- 返回:
- an instance of the bean (can be
null
) - 另请参阅:
FactoryBeanNotInitializedException
getObjectType
public Class<?> getObjectType()
从接口复制的说明:FactoryBean
Return the type of object that this FactoryBean creates, ornull
if 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
null
here. Therefore it is highly recommended to implement this method properly, using the current state of the FactoryBean.- 指定者:
getObjectType
在接口中FactoryBean<SessionFactory>
- 返回:
- the type of object that this FactoryBean creates, or
null
if not known at the time of the call - 另请参阅:
ListableBeanFactory.getBeansOfType(java.lang.Class<T>)
isSingleton
public boolean isSingleton()
从接口复制的说明:FactoryBean
Is 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 returntrue
unless 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
false
does not necessarily indicate that returned objects are independent instances. An implementation of the extendedSmartFactoryBean
interface may explicitly indicate independent instances through itsSmartFactoryBean.isPrototype()
method. PlainFactoryBean
implementations which do not implement this extended interface are simply assumed to always return independent instances if theisSingleton()
implementation returnsfalse
.The default implementation returns
true
, since aFactoryBean
typically manages a singleton instance.- 指定者:
isSingleton
在接口中FactoryBean<SessionFactory>
- 返回:
- whether the exposed object is a singleton
- 另请参阅:
FactoryBean.getObject()
,SmartFactoryBean.isPrototype()
destroy
public void destroy()
从接口复制的说明:DisposableBean
Invoked by the containingBeanFactory
on destruction of a bean.- 指定者:
destroy
在接口中DisposableBean