org.springframework.orm.hibernate3
Class LocalSessionFactoryBean

java.lang.Object
  extended by org.springframework.orm.hibernate3.LocalSessionFactoryBean
All Implemented Interfaces:
DisposableBean, FactoryBean, InitializingBean
Direct Known Subclasses:
AnnotationSessionFactoryBean

public class LocalSessionFactoryBean
extends Object
implements FactoryBean, InitializingBean, DisposableBean

FactoryBean that creates a local Hibernate SessionFactory instance. Behaves like a SessionFactory instance when used as bean reference, e.g. for HibernateTemplate's "sessionFactory" property.

The typical usage will be to register this as singleton factory (for a certain underlying JDBC DataSource) in an application context, and give bean references to application services that need it.

Configuration settings can either be read from a Hibernate XML file, specified as "configLocation", 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 "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 HibernateTransactionManager or JtaTransactionManager can be used for transaction demarcation, the latter only being necessary for transactions that span multiple databases.

This factory bean will by default expose a transaction-aware SessionFactory proxy, 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.

Requires Hibernate 3.0.3 or later. Note that this factory will use "on_close" as default Hibernate connection release mode, unless in the case of a "jtaTransactionManager" specified, for the reason that this is appropriate for most Spring-based applications (in particular when using Spring's HibernateTransactionManager). Hibernate 3.0 used "on_close" as its own default too; however, Hibernate 3.1 changed this to "auto" (i.e. "after_statement" or "after_transaction").

Since:
1.2
Author:
Juergen Hoeller
See Also:
HibernateAccessor.setSessionFactory(org.hibernate.SessionFactory), HibernateTransactionManager.setSessionFactory(org.hibernate.SessionFactory), setExposeTransactionAwareSessionFactory(boolean), setJtaTransactionManager(javax.transaction.TransactionManager), SessionFactory.getCurrentSession(), HibernateTransactionManager

Field Summary
protected  Log logger
           
 
Constructor Summary
LocalSessionFactoryBean()
           
 
Method Summary
 void afterPropertiesSet()
          Initialize the SessionFactory for the given or the default location.
 void createDatabaseSchema()
          Execute schema creation script, determined by the Configuration object used for creating the SessionFactory.
 void destroy()
          Close the SessionFactory on bean factory shutdown.
 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.
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.
 Configuration getConfiguration()
          Return the Configuration object used to build the SessionFactory.
 Properties getHibernateProperties()
          Return the Hibernate properties, if any.
 Object getObject()
          Return the singleton SessionFactory.
 Class getObjectType()
          Return the type of object that this FactoryBean creates, or null if not known in advance.
protected  SessionFactory getTransactionAwareSessionFactoryProxy(SessionFactory target)
          Wrap the given SessionFactory with a proxy that delegates every method call to it but delegates getCurrentSession calls to SessionFactoryUtils, for participating in Spring-managed transactions.
 boolean isSingleton()
          Is the bean managed by this factory a singleton or a prototype?
protected  Configuration newConfiguration()
          Subclasses can override this method to perform custom initialization of the Configuration instance used for SessionFactory creation.
protected  SessionFactory newSessionFactory(Configuration config)
          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.
protected  void postProcessConfiguration(Configuration config)
          To be implemented by subclasses that want to to perform custom post-processing of the Configuration object after this FactoryBean performed its default initialization.
 void setCacheableMappingLocations(Resource[] cacheableMappingLocations)
          Set locations of cacheable Hibernate mapping files, for example as web app resource "/WEB-INF/mapping/example.hbm.xml".
 void setCollectionCacheStrategies(Properties collectionCacheStrategies)
          Specify the cache strategies for persistent collections (with specific roles).
 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 setConfigurationClass(Class configurationClass)
          Specify the Hibernate Configuration class to use.
 void setDataSource(DataSource dataSource)
          Set the DataSource to be used by the SessionFactory.
 void setEntityCacheStrategies(Properties entityCacheStrategies)
          Specify the cache strategies for entities (persistent classes or named entities).
 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 setEventListeners(Map eventListeners)
          Specify the Hibernate event listeners to register, with listener types as keys and listener objects as values.
 void setExposeTransactionAwareSessionFactory(boolean exposeTransactionAwareSessionFactory)
          Set whether to expose a transaction-aware proxy for the SessionFactory, returning the Session that's associated with the current Spring-managed transaction on getCurrentSession(), if any.
 void setFilterDefinitions(FilterDefinition[] filterDefinitions)
          Specify the Hibernate FilterDefinitions to register with the SessionFactory.
 void setHibernateProperties(Properties hibernateProperties)
          Set Hibernate properties, such as "hibernate.dialect".
 void setJtaTransactionManager(TransactionManager jtaTransactionManager)
          Set the JTA TransactionManager to be used for Hibernate's TransactionManagerLookup.
 void setLobHandler(LobHandler lobHandler)
          Set the LobHandler to be used by the SessionFactory.
 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 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 setSchemaUpdate(boolean schemaUpdate)
          Set whether to execute a schema update after SessionFactory initialization.
 void setTypeDefinitions(TypeDefinitionBean[] typeDefinitions)
          Specify the Hibernate type definitions to register with the SessionFactory, as Spring TypeDefinitionBean instances.
 void 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.
 void updateDatabaseSchema()
          Execute schema update script, determined by the Configuration object used for creating the SessionFactory.
 
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
Constructor Detail

LocalSessionFactoryBean

public LocalSessionFactoryBean()
Method Detail

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

setConfigurationClass

public void setConfigurationClass(Class 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), Configuration, AnnotationConfiguration

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.

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

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.

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

setMappingResources

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

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

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

setMappingLocations

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

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

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

setCacheableMappingLocations

public void setCacheableMappingLocations(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)

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

setHibernateProperties

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

getHibernateProperties

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


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.

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), LocalDataSourceConnectionProvider, HibernateTransactionManager, JtaTransactionManager, LazyConnectionDataSourceProxy

setUseTransactionAwareDataSource

public void 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": LocalSessionFactoryBean is 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).

As a further effect, using a transaction-aware DataSource will apply remaining transaction timeouts to all created JDBC Statements. This means that all operations performed by the SessionFactory will automatically participate in Spring-managed transaction timeouts, not just queries. This adds value even for HibernateTransactionManager.

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 LocalSessionFactoryBean (for example, a JTA-aware DataSource fetched from JNDI), switch this setting to "true". Else, 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

setExposeTransactionAwareSessionFactory

public void setExposeTransactionAwareSessionFactory(boolean exposeTransactionAwareSessionFactory)
Set whether to expose a transaction-aware proxy for the SessionFactory, returning the Session that's associated with the current Spring-managed transaction on getCurrentSession(), 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, which only supports plain JTA synchronization through the JTA TransactionManager.

NOTE: The SessionFactory.getCurrentSession method is only available in Hibernate 3.0.1 and later. Before its introduction, DAOs coded against the plain Hibernate API had to manually open and close Sessions and care for transaction/request scoping.

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

setJtaTransactionManager

public void setJtaTransactionManager(TransactionManager jtaTransactionManager)
Set the JTA TransactionManager to be used for Hibernate's TransactionManagerLookup. If set, this will override corresponding settings in Hibernate properties. Allows to use 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

setLobHandler

public void 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

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.

Such an interceptor can either be set at the SessionFactory level, i.e. on LocalSessionFactoryBean, or at the Session level, i.e. on HibernateTemplate, HibernateInterceptor, and HibernateTransactionManager. It's preferable to set it on LocalSessionFactoryBean 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 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.

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

setEntityCacheStrategies

public void 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</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 void 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</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)

setTypeDefinitions

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

setFilterDefinitions

public void setFilterDefinitions(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)

setEventListeners

public void setEventListeners(Map eventListeners)
Specify the Hibernate event listeners to register, with listener types as keys and listener objects as values.

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)

setSchemaUpdate

public void 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

afterPropertiesSet

public void afterPropertiesSet()
                        throws IllegalArgumentException,
                               HibernateException,
                               IOException
Initialize the SessionFactory for the given or the default location.

Specified by:
afterPropertiesSet in interface InitializingBean
Throws:
IllegalArgumentException - in case of illegal property values
HibernateException - in case of Hibernate initialization errors
IOException

newConfiguration

protected Configuration newConfiguration()
                                  throws HibernateException
Subclasses can override this method to perform custom initialization of the Configuration instance used for SessionFactory creation. The properties of this LocalSessionFactoryBean will be applied to the Configuration object that gets returned here.

The default implementation creates a new Configuration instance. A custom implementation could prepare the instance in a specific way, or use a custom Configuration subclass.

Returns:
the Configuration instance
Throws:
HibernateException - in case of Hibernate initialization errors
See Also:
Configuration.Configuration()

postProcessConfiguration

protected void postProcessConfiguration(Configuration config)
                                 throws 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.

Parameters:
config - the current Configuration object
Throws:
HibernateException - in case of Hibernate initialization errors

newSessionFactory

protected SessionFactory newSessionFactory(Configuration config)
                                    throws 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 LocalSessionFactoryBean.

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 LocalSessionFactoryBean
Returns:
the SessionFactory instance
Throws:
HibernateException - in case of Hibernate initialization errors
See Also:
Configuration.buildSessionFactory()

getTransactionAwareSessionFactoryProxy

protected SessionFactory getTransactionAwareSessionFactoryProxy(SessionFactory target)
Wrap the given SessionFactory with a proxy that delegates every method call to it but delegates getCurrentSession calls to SessionFactoryUtils, for participating in Spring-managed transactions.

Parameters:
target - the original SessionFactory to wrap
Returns:
the wrapped SessionFactory
See Also:
SessionFactory.getCurrentSession(), SessionFactoryUtils.doGetSession(org.hibernate.SessionFactory, boolean)

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 LocalSessionFactoryBean itself rather than the exposed SessionFactory to be able to invoke this method, e.g. via LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");.

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)

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 LocalSessionFactoryBean itself rather than the exposed SessionFactory to be able to invoke this method, e.g. via LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");.

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 LocalSessionFactoryBean itself rather than the exposed SessionFactory to be able to invoke this method, e.g. via LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");.

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

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
con - the JDBC Connection to execute the script on
sql - the SQL statements to execute
Throws:
SQLException - if thrown by JDBC methods
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)

getConfiguration

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


getObject

public Object getObject()
Return the singleton SessionFactory.

Specified by:
getObject in interface FactoryBean
Returns:
an instance of the bean (should not be null; a null value will be considered as an indication of incomplete initialization)
See Also:
FactoryBeanNotInitializedException

getObjectType

public Class getObjectType()
Description copied from interface: FactoryBean
Return the type of object that this FactoryBean creates, or null if not known in advance. This allows to check for specific types of beans without instantiating objects, for example on autowiring.

For a singleton, this 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.

Specified by:
getObjectType in interface FactoryBean
Returns:
the type of object that this FactoryBean creates, or null if not known at the time of the call
See Also:
ListableBeanFactory.getBeansOfType(java.lang.Class)

isSingleton

public boolean isSingleton()
Description copied from interface: FactoryBean
Is the bean managed by this factory a singleton or a prototype? That is, will 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.

Specified by:
isSingleton in interface FactoryBean
Returns:
if this bean is a singleton
See Also:
FactoryBean.getObject()

destroy

public void destroy()
             throws HibernateException
Close the SessionFactory on bean factory shutdown.

Specified by:
destroy in interface DisposableBean
Throws:
HibernateException


Copyright (c) 2002-2007 The Spring Framework Project.