?? localsessionfactorybean.java
字號:
config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
}
}
}
if (this.collectionCacheStrategies != null) {
// Register cache strategies for mapped collections.
for (Enumeration collRoles = this.collectionCacheStrategies.propertyNames(); collRoles.hasMoreElements();) {
String collRole = (String) collRoles.nextElement();
String[] strategyAndRegion =
StringUtils.commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole));
if (strategyAndRegion.length > 1) {
config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0], strategyAndRegion[1]);
}
else if (strategyAndRegion.length > 0) {
config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
}
}
}
if (this.eventListeners != null) {
// Register specified Hibernate event listeners.
for (Iterator it = this.eventListeners.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Assert.isTrue(entry.getKey() instanceof String, "Event listener key needs to be of type String");
String listenerType = (String) entry.getKey();
Object listenerObject = entry.getValue();
if (listenerObject instanceof Collection) {
Collection listeners = (Collection) listenerObject;
EventListeners listenerRegistry = config.getEventListeners();
Object[] listenerArray =
(Object[]) Array.newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size());
listenerArray = listeners.toArray(listenerArray);
config.setListeners(listenerType, listenerArray);
}
else {
config.setListener(listenerType, listenerObject);
}
}
}
// Perform custom post-processing in subclasses.
postProcessConfiguration(config);
// Build SessionFactory instance.
logger.info("Building new Hibernate SessionFactory");
this.configuration = config;
return newSessionFactory(config);
}
finally {
if (dataSource != null) {
// Reset DataSource holder.
configTimeDataSourceHolder.set(null);
}
if (this.jtaTransactionManager != null) {
// Reset TransactionManager holder.
configTimeTransactionManagerHolder.set(null);
}
if (this.cacheProvider != null) {
// Reset CacheProvider holder.
configTimeCacheProviderHolder.set(null);
}
if (this.lobHandler != null) {
// Reset LobHandler holder.
configTimeLobHandlerHolder.set(null);
}
if (overrideClassLoader) {
// Reset original thread context ClassLoader.
currentThread.setContextClassLoader(threadContextClassLoader);
}
}
}
/**
* 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.
* <p>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.
* @return the Configuration instance
* @throws HibernateException in case of Hibernate initialization errors
* @see org.hibernate.cfg.Configuration#Configuration()
*/
protected Configuration newConfiguration() throws HibernateException {
return (Configuration) BeanUtils.instantiateClass(this.configurationClass);
}
/**
* To be implemented by subclasses that want to to register further mappings
* on the Configuration object after this FactoryBean registered its specified
* mappings.
* <p>Invoked <i>before</i> the <code>Configuration.buildMappings()</code> call,
* so that it can still extend and modify the mapping information.
* @param config the current Configuration object
* @throws HibernateException in case of Hibernate initialization errors
* @see org.hibernate.cfg.Configuration#buildMappings()
*/
protected void postProcessMappings(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.
* <p>Invoked <i>after</i> the <code>Configuration.buildMappings()</code> call,
* so that it can operate on the completed and fully parsed mapping information.
* @param config the current Configuration object
* @throws HibernateException in case of Hibernate initialization errors
* @see org.hibernate.cfg.Configuration#buildMappings()
*/
protected void postProcessConfiguration(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.
* <p>The default implementation invokes Configuration's buildSessionFactory.
* A custom implementation could prepare the instance in a specific way,
* or use a custom SessionFactoryImpl subclass.
* @param config Configuration prepared by this LocalSessionFactoryBean
* @return the SessionFactory instance
* @throws HibernateException in case of Hibernate initialization errors
* @see org.hibernate.cfg.Configuration#buildSessionFactory
*/
protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
return config.buildSessionFactory();
}
/**
* Return the Configuration object used to build the SessionFactory.
* Allows access to configuration metadata stored there (rarely needed).
* @throws IllegalStateException if the Configuration object has not been initialized yet
*/
public final Configuration getConfiguration() {
if (this.configuration == null) {
throw new IllegalStateException("Configuration not initialized yet");
}
return this.configuration;
}
/**
* Executes schema update if requested.
* @see #setSchemaUpdate
* @see #updateDatabaseSchema()
*/
protected void afterSessionFactoryCreation() throws Exception {
if (this.schemaUpdate) {
DataSource dataSource = getDataSource();
if (dataSource != null) {
// Make given DataSource available for the schema update,
// which unfortunately reinstantiates a ConnectionProvider.
configTimeDataSourceHolder.set(dataSource);
}
try {
updateDatabaseSchema();
}
finally {
if (dataSource != null) {
// Reset DataSource holder.
configTimeDataSourceHolder.set(null);
}
}
}
}
/**
* Allows for schema export on shutdown.
*/
public void destroy() throws HibernateException {
DataSource dataSource = getDataSource();
if (dataSource != null) {
// Make given DataSource available for potential SchemaExport,
// which unfortunately reinstantiates a ConnectionProvider.
configTimeDataSourceHolder.set(dataSource);
}
try {
super.destroy();
}
finally {
if (dataSource != null) {
// Reset DataSource holder.
configTimeDataSourceHolder.set(null);
}
}
}
/**
* 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.
* <p>Fetch the LocalSessionFactoryBean itself rather than the exposed
* SessionFactory to be able to invoke this method, e.g. via
* <code>LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");</code>.
* <p>Uses the SessionFactory that this bean generates for accessing a JDBC
* connection to perform the script.
* @throws org.springframework.dao.DataAccessException in case of script execution errors
* @see org.hibernate.cfg.Configuration#generateDropSchemaScript
* @see org.hibernate.tool.hbm2ddl.SchemaExport#drop
*/
public void dropDatabaseSchema() throws DataAccessException {
logger.info("Dropping database schema for Hibernate SessionFactory");
HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory());
hibernateTemplate.execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Connection con = session.connection();
Dialect dialect = Dialect.getDialect(getConfiguration().getProperties());
String[] sql = getConfiguration().generateDropSchemaScript(dialect);
executeSchemaScript(con, sql);
return null;
}
}
);
}
/**
* 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.
* <p>Fetch the LocalSessionFactoryBean itself rather than the exposed
* SessionFactory to be able to invoke this method, e.g. via
* <code>LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");</code>.
* <p>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 org.hibernate.cfg.Configuration#generateSchemaCreationScript
* @see org.hibernate.tool.hbm2ddl.SchemaExport#create
*/
public void createDatabaseSchema() throws DataAccessException {
logger.info("Creating database schema for Hibernate SessionFactory");
HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory());
hibernateTemplate.execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Connection con = session.connection();
Dialect dialect = Dialect.getDialect(getConfiguration().getProperties());
String[] sql = getConfiguration().generateSchemaCreationScript(dialect);
executeSchemaScript(con, sql);
return null;
}
}
);
}
/**
* 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.
* <p>Fetch the LocalSessionFactoryBean itself rather than the exposed
* SessionFactory to be able to invoke this method, e.g. via
* <code>LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");</code>.
* <p>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 #setSchemaUpdate
* @see org.hibernate.cfg.Configuration#generateSchemaUpdateScript
* @see org.hibernate.tool.hbm2ddl.SchemaUpdate
*/
public void updateDatabaseSchema() throws DataAccessException {
logger.info("Updating database schema for Hibernate SessionFactory");
HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory());
hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER);
hibernateTemplate.execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Connection con = session.connection();
Dialect dialect = Dialect.getDialect(getConfiguration().getProperties());
DatabaseMetadata metadata = new DatabaseMetadata(con, dialect);
String[] sql = getConfiguration().generateSchemaUpdateScript(dialect, metadata);
executeSchemaScript(con, sql);
return null;
}
}
);
}
/**
* Execute the given schema script on the given JDBC Connection.
* <p>Note that the default implementation will log unsuccessful statements
* and continue to execute. Override the <code>executeSchemaStatement</code>
* method to treat failures differently.
* @param con the JDBC Connection to execute the script on
* @param sql the SQL statements to execute
* @throws SQLException if thrown by JDBC methods
* @see #executeSchemaStatement
*/
protected void executeSchemaScript(Connection con, String[] sql) throws SQLException {
if (sql != null && sql.length > 0) {
boolean oldAutoCommit = con.getAutoCommit();
if (!oldAutoCommit) {
con.setAutoCommit(true);
}
try {
Statement stmt = con.createStatement();
try {
for (int i = 0; i < sql.length; i++) {
executeSchemaStatement(stmt, sql[i]);
}
}
finally {
JdbcUtils.closeStatement(stmt);
}
}
finally {
if (!oldAutoCommit) {
con.setAutoCommit(false);
}
}
}
}
/**
* Execute the given schema SQL on the given JDBC Statement.
* <p>Note that the default implementation will log unsuccessful statements
* and continue to execute. Override this method to treat failures differently.
* @param stmt the JDBC Statement to execute the SQL on
* @param sql the SQL statement to execute
* @throws SQLException if thrown by JDBC methods (and considered fatal)
*/
protected void executeSchemaStatement(Statement stmt, String sql) throws SQLException {
if (logger.isDebugEnabled()) {
logger.debug("Executing schema statement: " + sql);
}
try {
stmt.executeUpdate(sql);
}
catch (SQLException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Unsuccessful schema statement: " + sql, ex);
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -