|
|||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object org.springframework.orm.hibernate.LocalSessionFactoryBean
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).
HibernateAccessor.setSessionFactory(net.sf.hibernate.SessionFactory)
,
HibernateTransactionManager.setSessionFactory(net.sf.hibernate.SessionFactory)
,
JndiObjectFactoryBean
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. |
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. |
Object |
getObject()
Return the singleton SessionFactory. |
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 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 |
setConfigLocation(Resource configLocation)
Set the location of the Hibernate XML config file, for example as classpath resource "classpath:hibernate.cfg.xml". |
void |
setDataSource(DataSource dataSource)
Set the DataSource to be used by the SessionFactory. |
void |
setEntityInterceptor(Interceptor entityInterceptor)
Set a Hibernate entity interceptor that allows to inspect and change property values before writing to and reading from the database. |
void |
setHibernateProperties(Properties hibernateProperties)
Set Hibernate properties, like "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 |
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 |
protected final Log logger
Constructor Detail |
public LocalSessionFactoryBean()
Method Detail |
public static DataSource getConfigTimeDataSource()
This instance will be set before initialization of the corresponding SessionFactory, and reset immediately afterwards. It is thus only available during configuration.
setDataSource(javax.sql.DataSource)
,
LocalDataSourceConnectionProvider
public static TransactionManager getConfigTimeTransactionManager()
This instance will be set before initialization of the corresponding SessionFactory, and reset immediately afterwards. It is thus only available during configuration.
setJtaTransactionManager(javax.transaction.TransactionManager)
,
LocalTransactionManagerLookup
public static LobHandler getConfigTimeLobHandler()
This instance will be set before initialization of the corresponding SessionFactory, and reset immediately afterwards. It is thus only available during configuration.
setLobHandler(org.springframework.jdbc.support.lob.LobHandler)
,
ClobStringType
,
BlobByteArrayType
,
BlobSerializableType
public void setConfigLocation(Resource configLocation)
Note: Can be omitted when all necessary properties and mapping resources are specified locally via this bean.
Configuration.configure(java.net.URL)
public void setMappingResources(String[] mappingResources)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
setMappingLocations(org.springframework.core.io.Resource[])
,
Configuration.addResource(java.lang.String, java.lang.ClassLoader)
public void setMappingLocations(Resource[] mappingLocations)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
Configuration.addInputStream(java.io.InputStream)
public void setMappingJarLocations(Resource[] mappingJarLocations)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
Configuration.addJar(java.io.File)
public void setMappingDirectoryLocations(Resource[] mappingDirectoryLocations)
Can be used to add to mappings from a Hibernate XML config file, or to specify all mappings locally.
Configuration.addDirectory(java.io.File)
public void setHibernateProperties(Properties hibernateProperties)
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.
setDataSource(javax.sql.DataSource)
public void setDataSource(DataSource dataSource)
Note: 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 enlisting of JDBC Connections, LazyConnectionDataSourceProxy does not add value with JTA (i.e. Spring's JtaTransactionManager) as transaction strategy.
LocalDataSourceConnectionProvider
,
HibernateTransactionManager
,
JtaTransactionManager
,
LazyConnectionDataSourceProxy
public void setUseTransactionAwareDataSource(boolean useTransactionAwareDataSource)
Default is false: LocalSessionFactoryBean is usually used with Spring's HibernateTransactionManager or JtaTransactionManager, which expect the SessionFactory to work on the plain DataSource, with Hibernate Sessions managed by Spring's transaction infrastructure.
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.
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.
Note that this option does not add any value for JtaTransactionManager, or for HibernateTransactionManager in combination with HibernateTemplate. Transaction participation and transaction timeouts are already fully handled by that infrastructure combination. Just use it to let Hibernate participate in any other local transaction strategy, like DataSourceTransactionManager.
WARNING: Do not use a transaction-aware DataSource in combination with OpenSessionInViewFilter or OpenSessionInViewInterceptor. These Open Session In View providers are only properly supported in combination with HibernateTransactionManager or JtaTransactionManager, as stated in their javadoc.
setDataSource(javax.sql.DataSource)
,
TransactionAwareDataSourceProxy
,
DataSourceTransactionManager
,
HibernateTransactionManager
,
HibernateTemplate
,
OpenSessionInViewFilter
,
OpenSessionInViewInterceptor
,
SessionFactory.openSession(java.sql.Connection)
public void setJtaTransactionManager(TransactionManager jtaTransactionManager)
Note: If this is set, the Hibernate settings should not define a transaction manager lookup to avoid meaningless double configuration.
LocalTransactionManagerLookup
public void setLobHandler(LobHandler lobHandler)
getConfigTimeLobHandler()
,
UserType
,
ClobStringType
,
BlobByteArrayType
,
BlobSerializableType
public void setEntityInterceptor(Interceptor entityInterceptor)
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.
HibernateAccessor.setEntityInterceptor(net.sf.hibernate.Interceptor)
,
HibernateAccessor.setEntityInterceptor(net.sf.hibernate.Interceptor)
,
HibernateTransactionManager.setEntityInterceptor(net.sf.hibernate.Interceptor)
,
Configuration.setInterceptor(net.sf.hibernate.Interceptor)
public void setNamingStrategy(NamingStrategy namingStrategy)
Configuration.setNamingStrategy(net.sf.hibernate.cfg.NamingStrategy)
public void setSchemaUpdate(boolean schemaUpdate)
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.
Configuration.generateSchemaUpdateScript(net.sf.hibernate.dialect.Dialect, net.sf.hibernate.tool.hbm2ddl.DatabaseMetadata)
,
SchemaUpdate
public void afterPropertiesSet() throws IllegalArgumentException, HibernateException, IOException
afterPropertiesSet
in interface InitializingBean
IllegalArgumentException
- in case of illegal property values
HibernateException
- in case of Hibernate initialization errors
IOException
protected Configuration newConfiguration() throws HibernateException
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.
HibernateException
- in case of Hibernate initialization errorsConfiguration.Configuration()
protected void postProcessConfiguration(Configuration config) throws HibernateException
config
- the current Configuration object
HibernateException
- in case of Hibernate initialization errorsprotected SessionFactory newSessionFactory(Configuration config) throws HibernateException
The default implementation invokes Configuration's buildSessionFactory. A custom implementation could prepare the instance in a specific way, or use a custom SessionFactoryImpl subclass.
config
- Configuration prepared by this LocalSessionFactoryBean
HibernateException
- in case of Hibernate initialization errorsConfiguration.buildSessionFactory()
public void dropDatabaseSchema() throws DataAccessException
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.
DataAccessException
- in case of script execution errorsConfiguration.generateDropSchemaScript(net.sf.hibernate.dialect.Dialect)
,
SchemaExport.drop(boolean, boolean)
public void createDatabaseSchema() throws DataAccessException
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.
DataAccessException
- in case of script execution errorsConfiguration.generateSchemaCreationScript(net.sf.hibernate.dialect.Dialect)
,
SchemaExport.create(boolean, boolean)
public void updateDatabaseSchema() throws HibernateException
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.
HibernateException
- in case of Hibernate initialization errorssetSchemaUpdate(boolean)
,
Configuration.generateSchemaUpdateScript(net.sf.hibernate.dialect.Dialect, net.sf.hibernate.tool.hbm2ddl.DatabaseMetadata)
,
SchemaUpdate
protected void executeSchemaScript(Connection con, String[] sql) throws SQLException
con
- the JDBC Connection to execute the script onsql
- the SQL statements to execute
SQLException
- if thrown by JDBC methodspublic Configuration getConfiguration()
public Object getObject()
getObject
in interface FactoryBean
FactoryBeanNotInitializedException
public Class getObjectType()
FactoryBean
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.
getObjectType
in interface FactoryBean
ListableBeanFactory.getBeansOfType(java.lang.Class)
public boolean isSingleton()
FactoryBean
The singleton status of the FactoryBean itself will generally be provided by the owning BeanFactory; usually, it has to be defined as singleton there.
isSingleton
in interface FactoryBean
public void destroy() throws HibernateException
destroy
in interface DisposableBean
HibernateException
|
|||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |