org.springframework.orm.hibernate
Class LocalSessionFactoryBean

java.lang.Object
  extended byorg.springframework.orm.hibernate.LocalSessionFactoryBean
All Implemented Interfaces:
DisposableBean, FactoryBean, InitializingBean

public class LocalSessionFactoryBean
extends java.lang.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. Note that switching to JndiObjectFactoryBean is just a matter of configuration!

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.

Registering a SessionFactory with JNDI is only advisable when using Hibernate's JCA Connector, i.e. when the application server cares for initialization. Else, portability is rather limited: Manual JNDI binding isn't supported by some application servers (e.g. Tomcat). Unfortunately, JCA has drawbacks too: Its setup is container-specific and can be tedious.

Note that the JCA Connector's sole major strength is its seamless cooperation with EJB containers and JTA services. If you do not use EJB and initiate your JTA transactions via Spring's JtaTransactionManager, you can get all benefits including distributed transactions and proper transactional JVM-level caching with local SessionFactory setup too - without any configuration hassle like container-specific setup.

Note: Spring's Hibernate support requires Hibernate 2.1 (as of Spring 1.0).

Since:
05.05.2003
Author:
Juergen Hoeller
See Also:
HibernateAccessor.setSessionFactory(net.sf.hibernate.SessionFactory), HibernateTransactionManager.setSessionFactory(net.sf.hibernate.SessionFactory), JndiObjectFactoryBean

Field Summary
protected  org.apache.commons.logging.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(java.sql.Connection con, java.lang.String[] sql)
          Execute the given schema script on the given JDBC Connection.
static javax.sql.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 Type implementations like ClobStringType.
static javax.transaction.TransactionManager getConfigTimeTransactionManager()
          Return the JTA TransactionManager for the currently configured Hibernate SessionFactory, to be used by LocalTransactionManagerLookup.
 net.sf.hibernate.cfg.Configuration getConfiguration()
          Return the Configuration object used to build the SessionFactory.
 java.lang.Object getObject()
          Return the singleton SessionFactory.
 java.lang.Class getObjectType()
          Return the type of object that this FactoryBean creates, or null if not known in advance.
 boolean isSingleton()
          Is the bean managed by this factory a singleton or a prototype?
protected  net.sf.hibernate.cfg.Configuration newConfiguration()
          Subclasses can override this method to perform custom initialization of the Configuration instance used for SessionFactory creation.
protected  net.sf.hibernate.SessionFactory newSessionFactory(net.sf.hibernate.cfg.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(net.sf.hibernate.cfg.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 setConfigLocation(Resource configLocation)
          Set the location of the Hibernate XML config file, for example as classpath resource "classpath:hibernate.cfg.xml".
 void setDataSource(javax.sql.DataSource dataSource)
          Set the DataSource to be used by the SessionFactory.
 void setEntityInterceptor(net.sf.hibernate.Interceptor entityInterceptor)
          Set a Hibernate entity interceptor that allows to inspect and change property values before writing to and reading from the database.
 void setHibernateProperties(java.util.Properties hibernateProperties)
          Set Hibernate properties, like "hibernate.dialect".
 void setJtaTransactionManager(javax.transaction.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(java.lang.String[] mappingResources)
          Set Hibernate mapping resources to be found in the class path, like "example.hbm.xml" or "mypackage/example.hbm.xml".
 void setNamingStrategy(net.sf.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.
 void setSchemaUpdate(boolean schemaUpdate)
          Set whether to execute a schema update after SessionFactory initialization.
 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 org.apache.commons.logging.Log logger
Constructor Detail

LocalSessionFactoryBean

public LocalSessionFactoryBean()
Method Detail

getConfigTimeDataSource

public static javax.sql.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 javax.transaction.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 Type 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

setConfigLocation

public void setConfigLocation(Resource configLocation)
Set the location of the 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)

setMappingResources

public void setMappingResources(java.lang.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)

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(java.util.Properties hibernateProperties)
Set Hibernate properties, like "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)

setDataSource

public void setDataSource(javax.sql.DataSource dataSource)
Set the DataSource to be used by the SessionFactory. If set, this will override corresponding settings in Hibernate properties.

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

See Also:
LocalDataSourceConnectionProvider

setJtaTransactionManager

public void setJtaTransactionManager(javax.transaction.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 Type implementations.

See Also:
getConfigTimeLobHandler(), ClobStringType, BlobByteArrayType, Type

setEntityInterceptor

public void setEntityInterceptor(net.sf.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 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(net.sf.hibernate.Interceptor), HibernateAccessor.setEntityInterceptor(net.sf.hibernate.Interceptor), HibernateTransactionManager.setEntityInterceptor(net.sf.hibernate.Interceptor), Configuration.setInterceptor(net.sf.hibernate.Interceptor)

setNamingStrategy

public void setNamingStrategy(net.sf.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(net.sf.hibernate.cfg.NamingStrategy)

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 net.sf.hibernate.cfg.Configuration as Hibernate's own SchemaUpdate tool.

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

afterPropertiesSet

public void afterPropertiesSet()
                        throws java.lang.IllegalArgumentException,
                               net.sf.hibernate.HibernateException,
                               java.io.IOException
Initialize the SessionFactory for the given or the default location.

Specified by:
afterPropertiesSet in interface InitializingBean
Throws:
java.lang.IllegalArgumentException - in case of illegal property values
net.sf.hibernate.HibernateException - in case of Hibernate initialization errors
java.io.IOException

newConfiguration

protected net.sf.hibernate.cfg.Configuration newConfiguration()
                                                       throws net.sf.hibernate.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:
net.sf.hibernate.HibernateException - in case of Hibernate initialization errors
See Also:
Configuration.Configuration()

postProcessConfiguration

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

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

newSessionFactory

protected net.sf.hibernate.SessionFactory newSessionFactory(net.sf.hibernate.cfg.Configuration config)
                                                     throws net.sf.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 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:
net.sf.hibernate.HibernateException - in case of Hibernate initialization errors
See Also:
Configuration.buildSessionFactory()

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(net.sf.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(net.sf.hibernate.dialect.Dialect), SchemaExport.create(boolean, boolean)

updateDatabaseSchema

public void updateDatabaseSchema()
                          throws net.sf.hibernate.HibernateException
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:
net.sf.hibernate.HibernateException - in case of Hibernate initialization errors
See Also:
setSchemaUpdate(boolean), Configuration.generateSchemaUpdateScript(net.sf.hibernate.dialect.Dialect, net.sf.hibernate.tool.hbm2ddl.DatabaseMetadata), SchemaUpdate

executeSchemaScript

protected void executeSchemaScript(java.sql.Connection con,
                                   java.lang.String[] sql)
                            throws java.sql.SQLException
Execute the given schema script on the given JDBC Connection. Will log unsuccessful statements and continue to execute.

Parameters:
con - the JDBC Connection to execute the script on
sql - the SQL statements to execute
Throws:
java.sql.SQLException - if thrown by JDBC methods

getConfiguration

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


getObject

public java.lang.Object getObject()
Return the singleton SessionFactory.

Specified by:
getObject in interface FactoryBean
Returns:
an instance of the bean (should never be null)

getObjectType

public java.lang.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, e.g. on autowiring.

For a singleton, this can simply return getObject().getClass(), or even null, as autowiring will always check the actual objects for singletons. For prototypes, returning a meaningful type here is highly advisable, as autowiring will simply ignore them else.

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

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?

The singleton status of the FactoryBean itself will generally be provided by the owning BeanFactory.

Specified by:
isSingleton in interface FactoryBean
Returns:
if this bean is a singleton

destroy

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

Specified by:
destroy in interface DisposableBean
Throws:
net.sf.hibernate.HibernateException


Copyright (C) 2003-2004 The Spring Framework Project.