public class LocalSessionFactoryBean extends HibernateExceptionTranslator implements FactoryBean<SessionFactory>, ResourceLoaderAware, InitializingBean, 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 Hibernate-based data access objects via dependency injection.
This variant of LocalSessionFactoryBean requires Hibernate 4.0 or higher. As of Spring 4.0, it is compatible with (the quite refactored) Hibernate 4.3 as well. We recommend using the latest Hibernate 4.2.x or 4.3.x version, depending on whether you need to remain JPA 2.0 compatible at runtime (Hibernate 4.2) or can upgrade to JPA 2.1 (Hibernate 4.3).
This class is similar in role to the same-named class in the orm.hibernate3
package. However, in practice, it is closer to AnnotationSessionFactoryBean
since its core purpose is to bootstrap a SessionFactory
from package scanning.
NOTE: To set up Hibernate 4 for Spring-driven JTA transactions, make
sure to either specify the "jtaTransactionManager"
bean property or to set the "hibernate.transaction.factory_class" property to
CMTTransactionFactory
.
Otherwise, Hibernate's smart flushing mechanism won't work properly.
setDataSource(javax.sql.DataSource)
,
setPackagesToScan(java.lang.String...)
,
LocalSessionFactoryBuilder
Constructor and Description |
---|
LocalSessionFactoryBean() |
Modifier and Type | Method and Description |
---|---|
void |
afterPropertiesSet()
Invoked by the containing
BeanFactory after it has set all bean properties
and satisfied BeanFactoryAware , 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 containing
BeanFactory 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.
|
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,
or
null if not known in advance. |
boolean |
isSingleton()
Is the object managed by this factory a singleton? That is,
will
FactoryBean.getObject() always return the same object
(a reference that can be cached)? |
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 |
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 Hibernate RegionFactory 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(Object currentTenantIdentifierResolver)
Set a Hibernate 4.1/4.2/4.3
CurrentTenantIdentifierResolver to be passed
on to the SessionFactory: as an instance, a Class, or a String class name. |
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 |
setHibernateProperties(Properties hibernateProperties)
Set Hibernate properties, such as "hibernate.dialect".
|
void |
setJtaTransactionManager(Object jtaTransactionManager)
Set the Spring
JtaTransactionManager
or the JTA TransactionManager 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 |
setMultiTenantConnectionProvider(Object multiTenantConnectionProvider)
Set a Hibernate 4.1/4.2/4.3
MultiTenantConnectionProvider to be passed
on to the SessionFactory: as an instance, a Class, or a String class name. |
void |
setNamingStrategy(NamingStrategy namingStrategy)
Set a Hibernate NamingStrategy for the SessionFactory, determining the
physical column and table names given the info in the mapping document.
|
void |
setPackagesToScan(String... packagesToScan)
Specify packages to search for autodetection of your entity classes in the
classpath.
|
void |
setResourceLoader(ResourceLoader resourceLoader)
Set the ResourceLoader that this object runs in.
|
convertHibernateAccessException, translateExceptionIfPossible
public void setDataSource(DataSource dataSource)
If this is set, the Hibernate settings should not define a connection provider to avoid meaningless double configuration.
public void setConfigLocation(Resource configLocation)
Note: Can be omitted when all necessary properties and mapping resources are specified locally via this bean.
Configuration.configure(java.net.URL)
public void setConfigLocations(Resource... configLocations)
Note: Can be omitted when all necessary properties and mapping resources are specified locally via this bean.
Configuration.configure(java.net.URL)
public void setMappingResources(String... mappingResources)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
public void setMappingLocations(Resource... mappingLocations)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
public void setCacheableMappingLocations(Resource... cacheableMappingLocations)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
public void setMappingJarLocations(Resource... mappingJarLocations)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
Configuration.addJar(java.io.File)
public void setMappingDirectoryLocations(Resource... mappingDirectoryLocations)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
Configuration.addDirectory(java.io.File)
public void setEntityInterceptor(Interceptor entityInterceptor)
public void setNamingStrategy(NamingStrategy namingStrategy)
public void setJtaTransactionManager(Object jtaTransactionManager)
JtaTransactionManager
or the JTA TransactionManager
to be used with Hibernate,
if any. Implicitly sets up JtaPlatform
and CMTTransactionStrategy
.public void setMultiTenantConnectionProvider(Object multiTenantConnectionProvider)
MultiTenantConnectionProvider
to be passed
on to the SessionFactory: as an instance, a Class, or a String class name.
Note that the package location of the MultiTenantConnectionProvider
interface changed between Hibernate 4.2 and 4.3. This method accepts both variants.
LocalSessionFactoryBuilder.setMultiTenantConnectionProvider(java.lang.Object)
public void setCurrentTenantIdentifierResolver(Object currentTenantIdentifierResolver)
CurrentTenantIdentifierResolver
to be passed
on to the SessionFactory: as an instance, a Class, or a String class name.LocalSessionFactoryBuilder.setCurrentTenantIdentifierResolver(java.lang.Object)
public void setCacheRegionFactory(RegionFactory cacheRegionFactory)
Note: If this is set, the Hibernate settings should not define a cache provider to avoid meaningless double configuration.
public void setEntityTypeFilters(TypeFilter... entityTypeFilters)
Default is to search all specified packages for classes annotated with
@javax.persistence.Entity
, @javax.persistence.Embeddable
or @javax.persistence.MappedSuperclass
.
setPackagesToScan(java.lang.String...)
public void setHibernateProperties(Properties hibernateProperties)
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.
setDataSource(javax.sql.DataSource)
public Properties getHibernateProperties()
public void setAnnotatedClasses(Class<?>... annotatedClasses)
Configuration.addAnnotatedClass(Class)
public void setAnnotatedPackages(String... annotatedPackages)
Configuration.addPackage(String)
public void setPackagesToScan(String... packagesToScan)
ClassPathBeanDefinitionScanner
).public void setResourceLoader(ResourceLoader resourceLoader)
ResourceLoaderAware
This might be a ResourcePatternResolver, which can be checked
through instanceof ResourcePatternResolver
. See also the
ResourcePatternUtils.getResourcePatternResolver
method.
Invoked after population of normal bean properties but before an init callback
like InitializingBean's afterPropertiesSet
or a custom init-method.
Invoked before ApplicationContextAware's setApplicationContext
.
setResourceLoader
in interface ResourceLoaderAware
resourceLoader
- the ResourceLoader object to be used by this objectResourcePatternResolver
,
ResourcePatternUtils.getResourcePatternResolver(org.springframework.core.io.ResourceLoader)
public void afterPropertiesSet() throws IOException
InitializingBean
BeanFactory
after it has set all bean properties
and satisfied BeanFactoryAware
, 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
in interface InitializingBean
IOException
protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb)
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
- LocalSessionFactoryBuilder prepared by this LocalSessionFactoryBeanLocalSessionFactoryBuilder.buildSessionFactory()
public final Configuration getConfiguration()
IllegalStateException
- if the Configuration object has not been initialized yetpublic SessionFactory getObject()
FactoryBean
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
in interface FactoryBean<SessionFactory>
null
)FactoryBeanNotInitializedException
public Class<?> getObjectType()
FactoryBean
null
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
in interface FactoryBean<SessionFactory>
null
if not known at the time of the callListableBeanFactory.getBeansOfType(java.lang.Class<T>)
public boolean isSingleton()
FactoryBean
FactoryBean.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 return true
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 extended SmartFactoryBean
interface
may explicitly indicate independent instances through its
SmartFactoryBean.isPrototype()
method. Plain FactoryBean
implementations which do not implement this extended interface are
simply assumed to always return independent instances if the
isSingleton()
implementation returns false
.
isSingleton
in interface FactoryBean<SessionFactory>
FactoryBean.getObject()
,
SmartFactoryBean.isPrototype()
public void destroy()
DisposableBean
BeanFactory
on destruction of a bean.destroy
in interface DisposableBean