org.springframework.orm.hibernate3
Class SessionFactoryBuilderSupport<This extends SessionFactoryBuilderSupport<This>>

java.lang.Object
  extended by org.springframework.orm.hibernate3.SessionFactoryBuilderSupport<This>
Direct Known Subclasses:
AnnotationSessionFactoryBuilder, SessionFactoryBuilder

public abstract class SessionFactoryBuilderSupport<This extends SessionFactoryBuilderSupport<This>>
extends Object

Abstract base class for Spring's Hibernate SessionFactory *Builder and *FactoryBean types. Provides functionality suitable for setting up a shared Hibernate SessionFactory in a Spring application context; the SessionFactory can then be passed to Hibernate-based Repositories/DAOs via dependency injection.

Configuration settings can either be read from a Hibernate XML file, specified by the configLocation property, or completely via this class. A typical local configuration consists of one or more mappingResources, various hibernateProperties (not strictly necessary), and a dataSource that the SessionFactory should use. The latter can also be specified via Hibernate properties, but setDataSource(javax.sql.DataSource) supports any Spring-configured DataSource, instead of relying on Hibernate's own connection providers.

This SessionFactory handling strategy is appropriate for most types of applications, from Hibernate-only single database apps to ones that need distributed transactions. Either a HibernateTransactionManager or JtaTransactionManager can be used for transaction demarcation, with the latter only necessary for transactions which span multiple databases.

By default a transaction-aware SessionFactory proxy will be exposed, letting data access code work with the plain Hibernate SessionFactory and its getCurrentSession() method, while still being able to participate in current Spring-managed transactions: with any transaction management strategy, either local or JTA / EJB CMT, and any transaction synchronization mechanism, either Spring or JTA. Furthermore, getCurrentSession() will also seamlessly work with a request-scoped Session managed by OpenSessionInViewFilter or OpenSessionInViewInterceptor.

Requires Hibernate 3.2 or later; tested against 3.2, 3.3, 3.5 and 3.6. Note that this factory will use "on_close" as default Hibernate connection release mode, unless in the case of a jtaTransactionManager being specified, as this is appropriate for most Spring-based applications (in particular when using Spring's HibernateTransactionManager).

Concrete *Builder subclasses are designed for use within Spring @Configuration classes, while *FactoryBean subclasses are designed for use when configuring the container via Spring XML. See individual subclass documentation for complete details.

It is common to use the subclasses mentioned above in conjunction with Spring's HibernateExceptionTranslator and a PersistenceExceptionTranslationPostProcessor in order to convert native HibernateException types to Spring's DataAccessException hierarchy. *FactoryBean automatically perform translation through a built-in HibernateExceptionTranslator, but @Configuration class @Bean methods that use *Builder subclasses should manually register a HibernateExceptionTranslator @Bean. When using either type of subclass you must manually register a PersistenceExceptionTranslationPostProcessor bean.

Since:
3.1
Author:
Juergen Hoeller, Chris Beams
See Also:
SessionFactoryBuilder, LocalSessionFactoryBean, AnnotationSessionFactoryBuilder, AnnotationSessionFactoryBean, PersistenceExceptionTranslationPostProcessor, HibernateExceptionTranslator, HibernateAccessor.setSessionFactory(org.hibernate.SessionFactory), HibernateTransactionManager.setSessionFactory(org.hibernate.SessionFactory), setExposeTransactionAwareSessionFactory(boolean), setJtaTransactionManager(javax.transaction.TransactionManager), SessionFactory.getCurrentSession(), HibernateTransactionManager

Field Summary
protected  Log logger
          Logger available to subclasses
 
Constructor Summary
SessionFactoryBuilderSupport()
          Constructor for use when DataSource is not available as a Spring bean instance, i.e.: when DataSource configuration should be read from hibernate.cfg.xml
SessionFactoryBuilderSupport(DataSource dataSource)
           
 
Method Summary
protected  void afterSessionFactoryCreation()
          Executes schema update if requested.
protected  void beforeSessionFactoryDestruction()
          Hook that allows shutdown processing before the SessionFactory will be closed.
 org.hibernate.SessionFactory buildSessionFactory()
          Build the underlying Hibernate SessionFactory.
 void createDatabaseSchema()
          Execute schema creation script, determined by the Configuration object used for creating the SessionFactory.
protected  org.hibernate.SessionFactory doBuildSessionFactory()
          Populate the underlying Configuration instance with the various properties of this builder.
<C extends org.hibernate.cfg.Configuration>
This
doWithConfiguration(HibernateConfigurationCallback<C> callback)
          Use the given HibernateConfigurationCallback instance to configure this Builder's underlying Hibernate Configuration object.
 void dropDatabaseSchema()
          Execute schema drop script, determined by the Configuration object used for creating the SessionFactory.
protected  void executeSchemaScript(Connection con, String... sql)
          Execute the given schema script on the given JDBC Connection.
protected  void executeSchemaStatement(Statement stmt, String sql)
          Execute the given schema SQL on the given JDBC Statement.
protected  ClassLoader getBeanClassLoader()
           
protected  Object getCacheRegionFactory()
           
static DataSource getConfigTimeDataSource()
          Return the DataSource for the currently configured Hibernate SessionFactory, to be used by LocalDataSourceConnectionProvoder.
static LobHandler getConfigTimeLobHandler()
          Return the LobHandler for the currently configured Hibernate SessionFactory, to be used by UserType implementations like ClobStringType.
static TransactionManager getConfigTimeTransactionManager()
          Return the JTA TransactionManager for the currently configured Hibernate SessionFactory, to be used by LocalTransactionManagerLookup.
protected  org.hibernate.cfg.Configuration getConfiguration()
          Return the Hibernate Configuration object used to build the SessionFactory.
 DataSource getDataSource()
          Return the DataSource to be used by the SessionFactory.
protected abstract  Class<? extends org.hibernate.cfg.Configuration> getDefaultConfigurationClass()
          Return the default Configuration type used by this instance.
 Properties getHibernateProperties()
          Return the Hibernate properties, if any.
protected  org.hibernate.SessionFactory getSessionFactory()
          Return the exposed SessionFactory.
protected  boolean isExposeTransactionAwareSessionFactory()
          Return whether to expose a transaction-aware proxy for the SessionFactory.
protected  boolean isUseTransactionAwareDataSource()
          Return whether to use a transaction-aware DataSource for the SessionFactory.
protected  org.hibernate.cfg.Configuration newConfiguration()
          Instantiate and return an instance of the Configuration class type for this builder.
protected  org.hibernate.SessionFactory newSessionFactory()
          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 Builder.
protected  void postBuildSessionFactory()
          Allow cleaning up resources, thread locals, etc after building the SessionFactory.
protected  void postProcessConfiguration()
          To be implemented by subclasses that want to to perform custom post-processing of the Configuration object after this FactoryBean performed its default initialization.
protected  void postProcessMappings()
          To be implemented by subclasses that want to to register further mappings on the Configuration object after this FactoryBean registered its specified mappings.
protected  void preBuildSessionFactory()
          Allow additional population of the underlying Configuration instance.
 This setCacheableMappingLocations(Resource... cacheableMappingLocations)
          Set locations of cacheable Hibernate mapping files, for example as web app resource "/WEB-INF/mapping/example.hbm.xml".
 This setCacheRegionFactory(Object cacheRegionFactory)
          Set the Hibernate RegionFactory to use for the SessionFactory.
 This setClassLoader(ClassLoader beanClassLoader)
          Set the beanClassLoader for this instance.
 This setCollectionCacheStrategies(Properties collectionCacheStrategies)
          Specify the cache strategies for persistent collections (with specific roles).
 This setConfigLocation(Resource configLocation)
          Set the location of a single Hibernate XML config file, for example as classpath resource "classpath:hibernate.cfg.xml".
 This 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".
 This setConfigurationClass(Class<? extends org.hibernate.cfg.Configuration> configurationClass)
          Specify the Hibernate Configuration class to use.
 This setDataSource(DataSource dataSource)
          Set the DataSource to be used by the SessionFactory.
 This setEntityCacheStrategies(Properties entityCacheStrategies)
          Specify the cache strategies for entities (persistent classes or named entities).
 This setEntityInterceptor(org.hibernate.Interceptor entityInterceptor)
          Set a Hibernate entity interceptor that allows to inspect and change property values before writing to and reading from the database.
 This setEventListeners(Map<String,Object> eventListeners)
          Specify the Hibernate event listeners to register, with listener types as keys and listener objects as values.
 This setExposeTransactionAwareSessionFactory(boolean exposeTransactionAwareSessionFactory)
          Set whether to expose a transaction-aware current Session from the SessionFactory's getCurrentSession() method, returning the Session that's associated with the current Spring-managed transaction, if any.
 This setFilterDefinitions(org.hibernate.engine.FilterDefinition... filterDefinitions)
          Specify the Hibernate FilterDefinitions to register with the SessionFactory.
 This setHibernateProperties(Properties hibernateProperties)
          Set Hibernate properties, such as "hibernate.dialect".
 This setJtaTransactionManager(TransactionManager jtaTransactionManager)
          Set the JTA TransactionManager to be used for Hibernate's TransactionManagerLookup.
 This setLobHandler(LobHandler lobHandler)
          Set the LobHandler to be used by the SessionFactory.
 This setMappingDirectoryLocations(Resource... mappingDirectoryLocations)
          Set locations of directories that contain Hibernate mapping resources, like "WEB-INF/mappings".
 This setMappingJarLocations(Resource... mappingJarLocations)
          Set locations of jar files that contain Hibernate mapping resources, like "WEB-INF/lib/example.hbm.jar".
 This setMappingLocations(Resource... mappingLocations)
          Set locations of Hibernate mapping files, for example as classpath resource "classpath:example.hbm.xml".
 This setMappingResources(String... mappingResources)
          Set Hibernate mapping resources to be found in the class path, like "example.hbm.xml" or "mypackage/example.hbm.xml".
 This setNamingStrategy(org.hibernate.cfg.NamingStrategy namingStrategy)
          Set a Hibernate NamingStrategy for the SessionFactory, determining the physical column and table names given the info in the mapping document.
 This setSchemaUpdate(boolean schemaUpdate)
          Set whether to execute a schema update after SessionFactory initialization.
 This setTypeDefinitions(TypeDefinitionBean... typeDefinitions)
          Specify the Hibernate type definitions to register with the SessionFactory, as Spring TypeDefinitionBean instances.
 This setUseTransactionAwareDataSource(boolean useTransactionAwareDataSource)
          Set whether to use a transaction-aware DataSource for the SessionFactory, i.e.
 void updateDatabaseSchema()
          Execute schema update script, determined by the Configuration object used for creating the SessionFactory.
 void validateDatabaseSchema()
          Execute schema creation script, determined by the Configuration object used for creating the SessionFactory.
protected  org.hibernate.SessionFactory wrapSessionFactoryIfNecessary(org.hibernate.SessionFactory rawSf)
          Wrap the given SessionFactory with a proxy, if demanded.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

logger

protected final Log logger
Logger available to subclasses

Constructor Detail

SessionFactoryBuilderSupport

public SessionFactoryBuilderSupport()
Constructor for use when DataSource is not available as a Spring bean instance, i.e.: when DataSource configuration should be read from hibernate.cfg.xml

See Also:
SessionFactoryBuilderSupport#AbstractSessionFactoryBuilder(DataSource)

SessionFactoryBuilderSupport

public SessionFactoryBuilderSupport(DataSource dataSource)
Method Detail

getDefaultConfigurationClass

protected abstract Class<? extends org.hibernate.cfg.Configuration> getDefaultConfigurationClass()
Return the default Configuration type used by this instance. May be overridden with setConfigurationClass(Class).

See Also:
setConfigurationClass(Class)

buildSessionFactory

public org.hibernate.SessionFactory buildSessionFactory()
                                                 throws Exception
Build the underlying Hibernate SessionFactory.

Returns:
the raw SessionFactory (potentially to be wrapped with a transaction-aware proxy before it is exposed to the application)
Throws:
Exception - in case of initialization failure

doBuildSessionFactory

protected final org.hibernate.SessionFactory doBuildSessionFactory()
                                                            throws Exception
Populate the underlying Configuration instance with the various properties of this builder. Customization may be performed through pre* and post* methods.

Throws:
Exception
See Also:
preBuildSessionFactory(), postProcessMappings(), postBuildSessionFactory(), postBuildSessionFactory()

getConfiguration

protected final org.hibernate.cfg.Configuration getConfiguration()
Return the Hibernate Configuration object used to build the SessionFactory. Allows access to configuration metadata stored there (rarely needed).

Favor use of doWithConfiguration(HibernateConfigurationCallback) in order to customize the internal Configuration object.

Throws:
IllegalStateException - if the Configuration object has not been initialized yet
See Also:
doWithConfiguration(HibernateConfigurationCallback)

newConfiguration

protected org.hibernate.cfg.Configuration newConfiguration()
Instantiate and return an instance of the Configuration class type for this builder. Subclasses may override in order to customize instantiation logic, but clients should use doWithConfiguration(org.springframework.orm.hibernate3.HibernateConfigurationCallback) to directly customize the Configuration instance.

See Also:
getDefaultConfigurationClass(), setConfigurationClass(Class), getConfiguration(), doWithConfiguration(HibernateConfigurationCallback)

getSessionFactory

protected final org.hibernate.SessionFactory getSessionFactory()
Return the exposed SessionFactory. Will throw an exception if not initialized yet.

Returns:
the SessionFactory (never null)
Throws:
IllegalStateException - if the SessionFactory has not been initialized yet

preBuildSessionFactory

protected void preBuildSessionFactory()
Allow additional population of the underlying Configuration instance. Called during doBuildSessionFactory().


postBuildSessionFactory

protected void postBuildSessionFactory()
Allow cleaning up resources, thread locals, etc after building the SessionFactory. Called during the finally block of doBuildSessionFactory().


wrapSessionFactoryIfNecessary

protected org.hibernate.SessionFactory wrapSessionFactoryIfNecessary(org.hibernate.SessionFactory rawSf)
Wrap the given SessionFactory with a proxy, if demanded.

The default implementation wraps the given SessionFactory as a Spring DisposableBean proxy in order to call SessionFactory.close() on ApplicationContext shutdown.

Subclasses may override this to implement transaction awareness through a SessionFactory proxy for example, or even to avoid creation of the DisposableBean proxy altogether.

Parameters:
rawSf - the raw SessionFactory as built by buildSessionFactory()
Returns:
the SessionFactory reference to expose
See Also:
buildSessionFactory()

newSessionFactory

protected org.hibernate.SessionFactory newSessionFactory()
                                                  throws org.hibernate.HibernateException
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 Builder.

The default implementation invokes Configuration's buildSessionFactory. A custom implementation could prepare the instance in a specific way, or use a custom SessionFactoryImpl subclass.

Parameters:
config - Configuration prepared by this Builder
Returns:
the SessionFactory instance
Throws:
org.hibernate.HibernateException - in case of Hibernate initialization errors
See Also:
Configuration.buildSessionFactory()

postProcessMappings

protected void postProcessMappings()
                            throws org.hibernate.HibernateException
To be implemented by subclasses that want to to register further mappings on the Configuration object after this FactoryBean registered its specified mappings.

Invoked before the Configuration.buildMappings() call, so that it can still extend and modify the mapping information.

Parameters:
config - the current Configuration object
Throws:
org.hibernate.HibernateException - in case of Hibernate initialization errors
See Also:
Configuration.buildMappings()

postProcessConfiguration

protected void postProcessConfiguration()
                                 throws org.hibernate.HibernateException
To be implemented by subclasses that want to to perform custom post-processing of the Configuration object after this FactoryBean performed its default initialization.

Invoked after the Configuration.buildMappings() call, so that it can operate on the completed and fully parsed mapping information.

Throws:
org.hibernate.HibernateException - in case of Hibernate initialization errors
See Also:
Configuration.buildMappings()

afterSessionFactoryCreation

protected void afterSessionFactoryCreation()
                                    throws Exception
Executes schema update if requested.

Throws:
Exception
See Also:
setSchemaUpdate(boolean), updateDatabaseSchema()

beforeSessionFactoryDestruction

protected void beforeSessionFactoryDestruction()
Hook that allows shutdown processing before the SessionFactory will be closed. The SessionFactory is still available through getSessionFactory() at this point.

This implementation is empty.

See Also:
getSessionFactory()

createDatabaseSchema

public void createDatabaseSchema()
                          throws DataAccessException
Execute schema creation script, determined by the Configuration object used for creating the SessionFactory. A replacement for Hibernate's SchemaExport class, to be invoked on application setup.

Fetch the FactoryBean itself by rather than the exposed SessionFactory to be able to invoke this method, e.g. via

 LocalSessionFactoryBean sfb = ctx.getBean("&mySessionFactory", LocalSessionFactoryBean.class);
 
or in the case of @Configuration class usage, register the SessionFactoryBuilder as a @Bean and fetch it by type:
 SessionFactoryBuilder sfb = ctx.getBean(SessionFactoryBuilder.class);
 

Uses the SessionFactory that this bean generates for accessing a JDBC connection to perform the script.

Throws:
DataAccessException - in case of script execution errors
See Also:
Configuration.generateSchemaCreationScript(org.hibernate.dialect.Dialect), SchemaExport.create(boolean, boolean)

updateDatabaseSchema

public void updateDatabaseSchema()
                          throws DataAccessException
Execute schema update script, determined by the Configuration object used for creating the SessionFactory. A replacement for Hibernate's SchemaUpdate class, for automatically executing schema update scripts on application startup. Can also be invoked manually.

Fetch the FactoryBean itself by rather than the exposed SessionFactory to be able to invoke this method, e.g. via

 LocalSessionFactoryBean sfb = ctx.getBean("&mySessionFactory", LocalSessionFactoryBean.class);
 
or in the case of @Configuration class usage, register the SessionFactoryBuilder as a @Bean and fetch it by type:
 SessionFactoryBuilder sfb = ctx.getBean(SessionFactoryBuilder.class);
 

Uses the SessionFactory that this bean generates for accessing a JDBC connection to perform the script.

Throws:
DataAccessException - in case of script execution errors
See Also:
setSchemaUpdate(boolean), Configuration.generateSchemaUpdateScript(org.hibernate.dialect.Dialect, org.hibernate.tool.hbm2ddl.DatabaseMetadata), SchemaUpdate

validateDatabaseSchema

public void validateDatabaseSchema()
                            throws DataAccessException
Execute schema creation script, determined by the Configuration object used for creating the SessionFactory. A replacement for Hibernate's SchemaValidator class, to be invoked after application startup.

Fetch the FactoryBean itself by rather than the exposed SessionFactory to be able to invoke this method, e.g. via

 LocalSessionFactoryBean sfb = ctx.getBean("&mySessionFactory", LocalSessionFactoryBean.class);
 
or in the case of @Configuration class usage, register the SessionFactoryBuilder as a @Bean and fetch it by type:
 SessionFactoryBuilder sfb = ctx.getBean(SessionFactoryBuilder.class);
 

Uses the SessionFactory that this bean generates for accessing a JDBC connection to perform the script.

Throws:
DataAccessException - in case of script execution errors
See Also:
Configuration.validateSchema(org.hibernate.dialect.Dialect, org.hibernate.tool.hbm2ddl.DatabaseMetadata), SchemaValidator

dropDatabaseSchema

public void dropDatabaseSchema()
                        throws DataAccessException
Execute schema drop script, determined by the Configuration object used for creating the SessionFactory. A replacement for Hibernate's SchemaExport class, to be invoked on application setup.

Fetch the FactoryBean itself by rather than the exposed SessionFactory to be able to invoke this method, e.g. via

 LocalSessionFactoryBean sfb = ctx.getBean("&mySessionFactory", LocalSessionFactoryBean.class);
 
or in the case of @Configuration class usage, register the SessionFactoryBuilder as a @Bean and fetch it by type:
 SessionFactoryBuilder sfb = ctx.getBean(SessionFactoryBuilder.class);
 

Uses the SessionFactory that this bean generates for accessing a JDBC connection to perform the script.

Throws:
DataAccessException - in case of script execution errors
See Also:
Configuration.generateDropSchemaScript(org.hibernate.dialect.Dialect), SchemaExport.drop(boolean, boolean)

executeSchemaScript

protected void executeSchemaScript(Connection con,
                                   String... sql)
                            throws SQLException
Execute the given schema script on the given JDBC Connection.

Note that the default implementation will log unsuccessful statements and continue to execute. Override the executeSchemaStatement method to treat failures differently.

Parameters:
con - the JDBC Connection to execute the script on
sql - the SQL statements to execute
Throws:
SQLException - if thrown by JDBC methods
See Also:
executeSchemaStatement(java.sql.Statement, java.lang.String)

executeSchemaStatement

protected void executeSchemaStatement(Statement stmt,
                                      String sql)
                               throws SQLException
Execute the given schema SQL on the given JDBC Statement.

Note that the default implementation will log unsuccessful statements and continue to execute. Override this method to treat failures differently.

Parameters:
stmt - the JDBC Statement to execute the SQL on
sql - the SQL statement to execute
Throws:
SQLException - if thrown by JDBC methods (and considered fatal)

setConfigurationClass

public final This setConfigurationClass(Class<? extends org.hibernate.cfg.Configuration> configurationClass)
Specify the Hibernate Configuration class to use. Default is org.hibernate.cfg.Configuration; any subclass of this default Hibernate Configuration class can be specified.

Can be set to org.hibernate.cfg.AnnotationConfiguration for using Hibernate3 annotation support (initially only available as alpha download separate from the main Hibernate3 distribution).

Annotated packages and annotated classes can be specified via the corresponding tags in "hibernate.cfg.xml" then, so this will usually be combined with a "configLocation" property that points at such a standard Hibernate configuration file.

See Also:
setConfigLocation(org.springframework.core.io.Resource), doWithConfiguration(org.springframework.orm.hibernate3.HibernateConfigurationCallback), Configuration, AnnotationConfiguration

doWithConfiguration

public <C extends org.hibernate.cfg.Configuration> This doWithConfiguration(HibernateConfigurationCallback<C> callback)
                                                                    throws Exception
Use the given HibernateConfigurationCallback instance to configure this Builder's underlying Hibernate Configuration object.

The HibernateConfigurationCallback type may be parameterized to org.hibernate.cfg.Configuration (the default), or org.hibernate.cfg.AnnotationConfiguration if running a Hibernate version less than 3.6. Otherwise, may be parameterized to any custom Configuration class provided to setConfigurationClass(java.lang.Class)

Throws:
Exception - propagating any exception thrown during operations against the underlying Configuration object. @Bean methods should declare throws Exception when using this method, allowing the Spring container to deal with it and fail appropriately.
See Also:
setConfigurationClass(Class)

setDataSource

public This 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.

If using HibernateTransactionManager as transaction strategy, consider proxying your target DataSource with a LazyConnectionDataSourceProxy. This defers fetching of an actual JDBC Connection until the first JDBC Statement gets executed, even within JDBC transactions (as performed by HibernateTransactionManager). Such lazy fetching is particularly beneficial for read-only operations, in particular if the chances of resolving the result in the second-level cache are high.

As JTA and transactional JNDI DataSources already provide lazy enlistment of JDBC Connections, LazyConnectionDataSourceProxy does not add value with JTA (i.e. Spring's JtaTransactionManager) as transaction strategy.

See Also:
setUseTransactionAwareDataSource(boolean), HibernateTransactionManager, JtaTransactionManager, LazyConnectionDataSourceProxy

getDataSource

public DataSource getDataSource()
Return the DataSource to be used by the SessionFactory.


setConfigLocation

public This 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.

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

getHibernateProperties

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


setCacheableMappingLocations

public This 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(java.io.File)

setConfigLocations

public This 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.

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

setLobHandler

public This setLobHandler(LobHandler lobHandler)
Set the LobHandler to be used by the SessionFactory. Will be exposed at config time for UserType implementations.

See Also:
getConfigTimeLobHandler(), UserType, ClobStringType, BlobByteArrayType, BlobSerializableType

setCacheRegionFactory

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

As of Hibernate 3.3, this is the preferred mechanism for configuring caches, superseding the CacheProvider SPI. For Hibernate 3.2 compatibility purposes, the accepted reference is of type Object: the actual type is org.hibernate.cache.RegionFactory.

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

See Also:
RegionFactory

getCacheRegionFactory

protected Object getCacheRegionFactory()

setExposeTransactionAwareSessionFactory

public This setExposeTransactionAwareSessionFactory(boolean exposeTransactionAwareSessionFactory)
Set whether to expose a transaction-aware current Session from the SessionFactory's getCurrentSession() method, returning the Session that's associated with the current Spring-managed transaction, if any.

Default is "true", letting data access code work with the plain Hibernate SessionFactory and its getCurrentSession() method, while still being able to participate in current Spring-managed transactions: with any transaction management strategy, either local or JTA / EJB CMT, and any transaction synchronization mechanism, either Spring or JTA. Furthermore, getCurrentSession() will also seamlessly work with a request-scoped Session managed by OpenSessionInViewFilter/Interceptor.

Turn this flag off to expose the plain Hibernate SessionFactory with Hibernate's default getCurrentSession() behavior, supporting plain JTA synchronization only. Alternatively, simply override the corresponding Hibernate property "hibernate.current_session_context_class".

See Also:
SpringSessionContext, SessionFactory.getCurrentSession(), JtaTransactionManager, HibernateTransactionManager, OpenSessionInViewFilter, OpenSessionInViewInterceptor

isExposeTransactionAwareSessionFactory

protected boolean isExposeTransactionAwareSessionFactory()
Return whether to expose a transaction-aware proxy for the SessionFactory.


setUseTransactionAwareDataSource

public This setUseTransactionAwareDataSource(boolean useTransactionAwareDataSource)
Set whether to use a transaction-aware DataSource for the SessionFactory, i.e. whether to automatically wrap the passed-in DataSource with Spring's TransactionAwareDataSourceProxy.

Default is "false": SessionFactoryBuilder types are usually used with Spring's HibernateTransactionManager or JtaTransactionManager, both of which work nicely on a plain JDBC DataSource. Hibernate Sessions and their JDBC Connections are fully managed by the Hibernate/JTA transaction infrastructure in such a scenario.

If you switch this flag to "true", Spring's Hibernate access will be able to participate in JDBC-based transactions managed outside of Hibernate (for example, by Spring's DataSourceTransactionManager). This can be convenient if you need a different local transaction strategy for another O/R mapping tool, for example, but still want Hibernate access to join into those transactions.

A further benefit of this option is that plain Sessions opened directly via the SessionFactory, outside of Spring's Hibernate support, will still participate in active Spring-managed transactions. However, consider using Hibernate's getCurrentSession() method instead (see javadoc of "exposeTransactionAwareSessionFactory" property).

WARNING: When using a transaction-aware JDBC DataSource in combination with OpenSessionInViewFilter/Interceptor, whether participating in JTA or external JDBC-based transactions, it is strongly recommended to set Hibernate's Connection release mode to "after_transaction" or "after_statement", which guarantees proper Connection handling in such a scenario. In contrast to that, HibernateTransactionManager generally requires release mode "on_close".

Note: If you want to use Hibernate's Connection release mode "after_statement" with a DataSource specified on this SessionFactoryBuilder (for example, a JTA-aware DataSource fetched from JNDI), switch this setting to "true". Otherwise, the ConnectionProvider used underneath will vote against aggressive release and thus silently switch to release mode "after_transaction".

See Also:
setDataSource(javax.sql.DataSource), setExposeTransactionAwareSessionFactory(boolean), TransactionAwareDataSourceProxy, DataSourceTransactionManager, OpenSessionInViewFilter, OpenSessionInViewInterceptor, HibernateTransactionManager, JtaTransactionManager

isUseTransactionAwareDataSource

protected boolean isUseTransactionAwareDataSource()
Return whether to use a transaction-aware DataSource for the SessionFactory.


setJtaTransactionManager

public This setJtaTransactionManager(TransactionManager jtaTransactionManager)
Set the JTA TransactionManager to be used for Hibernate's TransactionManagerLookup. Allows for using a Spring-managed JTA TransactionManager for Hibernate's cache synchronization.

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

See Also:
LocalTransactionManagerLookup

setSchemaUpdate

public This setSchemaUpdate(boolean schemaUpdate)
Set whether to execute a schema update after SessionFactory initialization.

For details on how to make schema update scripts work, see the Hibernate documentation, as this class leverages the same schema update script support in org.hibernate.cfg.Configuration as Hibernate's own SchemaUpdate tool.

See Also:
Configuration.generateSchemaUpdateScript(org.hibernate.dialect.Dialect, org.hibernate.tool.hbm2ddl.DatabaseMetadata), SchemaUpdate

setClassLoader

public This setClassLoader(ClassLoader beanClassLoader)
Set the beanClassLoader for this instance. Not named setBeanClassLoader to allow subclasses to implement BeanClassLoaderAware without violating this method's signature. Any such implementation should simply delegate to this method.

See Also:
getBeanClassLoader()

getBeanClassLoader

protected ClassLoader getBeanClassLoader()
See Also:
setClassLoader(ClassLoader)

setMappingResources

public This 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)

setMappingJarLocations

public This 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(java.io.File)

setMappingDirectoryLocations

public This 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(java.io.File)

setMappingLocations

public This 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.

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

setHibernateProperties

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

Can be used to override values in a Hibernate XML config file, or to specify all necessary properties locally.

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)

setEntityInterceptor

public This setEntityInterceptor(org.hibernate.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.

Such an interceptor can either be set at the SessionFactory level, i.e. on SessionFactoryBuilder, or at the Session level, i.e. on HibernateTemplate, HibernateInterceptor, and HibernateTransactionManager. It's preferable to set it on SessionFactoryBuilder or HibernateTransactionManager to avoid repeated configuration and guarantee consistent behavior in transactions.

See Also:
HibernateAccessor.setEntityInterceptor(org.hibernate.Interceptor), HibernateAccessor.setEntityInterceptor(org.hibernate.Interceptor), HibernateTransactionManager.setEntityInterceptor(org.hibernate.Interceptor), Configuration.setInterceptor(org.hibernate.Interceptor)

setNamingStrategy

public This setNamingStrategy(org.hibernate.cfg.NamingStrategy namingStrategy)
Set a Hibernate NamingStrategy for the SessionFactory, determining the physical column and table names given the info in the mapping document.

See Also:
Configuration.setNamingStrategy(org.hibernate.cfg.NamingStrategy)

setEntityCacheStrategies

public This setEntityCacheStrategies(Properties entityCacheStrategies)
Specify the cache strategies for entities (persistent classes or named entities). This configuration setting corresponds to the <class-cache> entry in the "hibernate.cfg.xml" configuration format.

For example:

 <property name="entityCacheStrategies">
   <props>
     <prop key="com.mycompany.Customer">read-write</prop>
     <prop key="com.mycompany.Product">read-only,myRegion</prop>
   </props>
 </property>

Parameters:
entityCacheStrategies - properties that define entity cache strategies, with class names as keys and cache concurrency strategies as values
See Also:
Configuration.setCacheConcurrencyStrategy(String, String)

setCollectionCacheStrategies

public This setCollectionCacheStrategies(Properties collectionCacheStrategies)
Specify the cache strategies for persistent collections (with specific roles). This configuration setting corresponds to the <collection-cache> entry in the "hibernate.cfg.xml" configuration format.

For example:

 <property name="collectionCacheStrategies">
   <props>
     <prop key="com.mycompany.Order.items">read-write</prop>
     <prop key="com.mycompany.Product.categories">read-only,myRegion</prop>
   </props>
 </property>

Parameters:
collectionCacheStrategies - properties that define collection cache strategies, with collection roles as keys and cache concurrency strategies as values
See Also:
Configuration.setCollectionCacheConcurrencyStrategy(String, String)

setEventListeners

public This setEventListeners(Map<String,Object> eventListeners)
Specify the Hibernate event listeners to register, with listener types as keys and listener objects as values. Instead of a single listener object, you can also pass in a list or set of listeners objects as value.

See the Hibernate documentation for further details on listener types and associated listener interfaces.

Parameters:
eventListeners - Map with listener type Strings as keys and listener objects as values
See Also:
Configuration.setListener(String, Object)

setFilterDefinitions

public This setFilterDefinitions(org.hibernate.engine.FilterDefinition... filterDefinitions)
Specify the Hibernate FilterDefinitions to register with the SessionFactory. This is an alternative to specifying <filter-def> elements in Hibernate mapping files.

Typically, the passed-in FilterDefinition objects will have been defined as Spring FilterDefinitionFactoryBeans, probably as inner beans within the LocalSessionFactoryBean definition.

See Also:
FilterDefinitionFactoryBean, Configuration.addFilterDefinition(org.hibernate.engine.FilterDefinition)

setTypeDefinitions

public This setTypeDefinitions(TypeDefinitionBean... typeDefinitions)
Specify the Hibernate type definitions to register with the SessionFactory, as Spring TypeDefinitionBean instances. This is an alternative to specifying <typedef> elements in Hibernate mapping files.

Unfortunately, Hibernate itself does not define a complete object that represents a type definition, hence the need for Spring's TypeDefinitionBean.

See Also:
TypeDefinitionBean, Mappings.addTypeDef(String, String, java.util.Properties)

getConfigTimeDataSource

public static DataSource getConfigTimeDataSource()
Return the DataSource for the currently configured Hibernate SessionFactory, to be used by LocalDataSourceConnectionProvoder.

This instance will be set before initialization of the corresponding SessionFactory, and reset immediately afterwards. It is thus only available during configuration.

See Also:
setDataSource(javax.sql.DataSource), LocalDataSourceConnectionProvider

getConfigTimeTransactionManager

public static TransactionManager getConfigTimeTransactionManager()
Return the JTA TransactionManager for the currently configured Hibernate SessionFactory, to be used by LocalTransactionManagerLookup.

This instance will be set before initialization of the corresponding SessionFactory, and reset immediately afterwards. It is thus only available during configuration.

See Also:
setJtaTransactionManager(javax.transaction.TransactionManager), LocalTransactionManagerLookup

getConfigTimeLobHandler

public static LobHandler getConfigTimeLobHandler()
Return the LobHandler for the currently configured Hibernate SessionFactory, to be used by UserType implementations like ClobStringType.

This instance will be set before initialization of the corresponding SessionFactory, and reset immediately afterwards. It is thus only available during configuration.

See Also:
setLobHandler(org.springframework.jdbc.support.lob.LobHandler), ClobStringType, BlobByteArrayType, BlobSerializableType