Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Revert "Introduce (Annotation)SessionFactoryBuilder types"

This commit and the several before it back out the
SessionFactoryBuilder and AnnotationSessionFactoryBuilder types
recently introduced in 3.1 M2. This is in light of the impending
release of Hibernate 4.0 GA and our own support for it the new
org.springframework.orm.hibernate4 package (not yet committed).

This new package will have a similar, but far simpler, arrangement of
a single LocalSessionFactoryBuilder and LocalSessionFactoryBean pair.
Hibernate 3.x support will remain largely as-is, however the
HibernateTransactionManager introduced with SPR-8076 will remain.

This reverts commit 9e82591.

Issue: SPR-8066, SPR-7936, SPR-8076, SPR-8098, SPR-8096, SPR-7387

git-svn-id: https://src.springframework.org/svn/spring-framework/trunk@5044 50f2f4bb-b051-0410-bef5-90022cba6387
  • Loading branch information...
commit 011e123e3fbc0a42600f60dec01f9d2ba02478ae 1 parent cec2c4c
@cbeams authored
Showing with 1,745 additions and 3,012 deletions.
  1. +0 −1  org.springframework.integration-tests/integration-tests.iml
  2. +0 −2  org.springframework.integration-tests/ivy.xml
  3. +0 −340 ...ation-tests/src/test/java/org/springframework/orm/hibernate3/HibernateSessionFactoryConfigurationTests.java
  4. +0 −36 org.springframework.integration-tests/src/test/java/org/springframework/orm/hibernate3/scannable/Foo.java
  5. +0 −12 ...sts/src/test/resources/org/springframework/orm/hibernate3/AnnotationSessionFactoryBeanXmlConfig-context.xml
  6. +0 −18 ...on-tests/src/test/resources/org/springframework/orm/hibernate3/LocalSessionFactoryBeanXmlConfig-context.xml
  7. +0 −12 ...mework.integration-tests/src/test/resources/org/springframework/orm/hibernate3/scannable/FooMapping.hbm.xml
  8. +336 −0 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/AbstractSessionFactoryBean.java
  9. +18 −19 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/FilterDefinitionFactoryBean.java
  10. +8 −9 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateAccessor.java
  11. +0 −41 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateConfigurationCallback.java
  12. +7 −6 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTemplate.java
  13. +10 −16 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java
  14. +2 −9 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalCacheProviderProxy.java
  15. +7 −8 ...springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalDataSourceConnectionProvider.java
  16. +2 −2 ...ingframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalJtaDataSourceConnectionProvider.java
  17. +5 −5 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalRegionFactoryProxy.java
  18. +1,054 −70 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java
  19. +6 −6 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalTransactionManagerLookup.java
  20. +0 −198 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryBeanDelegate.java
  21. +0 −128 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryBeanOperations.java
  22. +0 −101 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryBuilder.java
  23. +0 −1,408 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryBuilderSupport.java
  24. +2 −2 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryUtils.java
  25. +3 −4 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SpringSessionContext.java
  26. +3 −3 ...work.orm/src/main/java/org/springframework/orm/hibernate3/TransactionAwareDataSourceConnectionProvider.java
  27. +12 −13 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/TypeDefinitionBean.java
  28. +171 −107 ...framework.orm/src/main/java/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.java
  29. +0 −300 ...mework.orm/src/main/java/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBuilder.java
  30. +19 −13 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/AbstractLobType.java
  31. +7 −7 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/BlobByteArrayType.java
  32. +7 −7 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/BlobSerializableType.java
  33. +7 −7 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/BlobStringType.java
  34. +7 −7 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/ClobStringType.java
  35. +3 −5 ...ramework.orm/src/main/java/org/springframework/orm/hibernate3/support/IdTransferringMergeEventListener.java
  36. +7 −9 org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/ScopedBeanInterceptor.java
  37. +5 −10 org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java
  38. +37 −71 org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java
View
1  org.springframework.integration-tests/integration-tests.iml
@@ -33,7 +33,6 @@
<orderEntry type="library" name="Hamcrest" level="project" />
<orderEntry type="library" name="JUnit" level="project" />
<orderEntry type="library" name="Log4j" level="project" />
- <orderEntry type="library" name="SLF4j" level="project" />
<orderEntry type="module-library">
<library>
<CLASSES>
View
2  org.springframework.integration-tests/ivy.xml
@@ -74,9 +74,7 @@
<dependency org="org.hibernate" name="com.springsource.org.hibernate.annotations.common" rev="3.3.0.ga" conf="test->compile"/>
<dependency org="org.hibernate" name="com.springsource.org.hibernate.ejb" rev="3.4.0.GA" conf="test->compile"/>
<dependency org="org.hsqldb" name="com.springsource.org.hsqldb" rev="1.8.0.9" conf="test->compile"/>
- <dependency org="org.jboss.javassist" name="com.springsource.javassist" rev="3.3.0.ga" conf="test->runtime"/>
<dependency org="org.jruby" name="com.springsource.org.jruby" rev="1.4.0" conf="optional, runtime->compile"/>
- <dependency org="org.slf4j" name="com.springsource.slf4j.jcl" rev="${slf4j.version}" conf="test->runtime"/>
<dependency org="org.springframework" name="org.springframework.asm" rev="latest.integration" conf="test->runtime"/>
<dependency org="org.springframework" name="org.springframework.aop" rev="latest.integration" conf="test->compile"/>
<dependency org="org.springframework" name="org.springframework.beans" rev="latest.integration" conf="test->compile"/>
View
340 ...st/java/org/springframework/orm/hibernate3/HibernateSessionFactoryConfigurationTests.java
@@ -1,340 +0,0 @@
-/*
- * Copyright 2002-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.orm.hibernate3;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-import java.io.File;
-import java.util.List;
-
-import javax.inject.Inject;
-import javax.sql.DataSource;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-import org.hibernate.cfg.AnnotationConfiguration;
-import org.hibernate.classic.Session;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.springframework.beans.factory.BeanCreationException;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.ImportResource;
-import org.springframework.dao.DataAccessException;
-import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
-import org.springframework.dao.support.PersistenceExceptionTranslator;
-import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
-import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
-import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBuilder;
-import org.springframework.orm.hibernate3.scannable.Foo;
-import org.springframework.stereotype.Repository;
-import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.annotation.EnableTransactionManagement;
-import org.springframework.transaction.annotation.Transactional;
-
-/**
- * Integration tests for configuring Hibernate SessionFactory types
- * without using a FactoryBean, e.g., within a {@link Configuration} class.
- *
- * @author Chris Beams
- * @since 3.1
- */
-public class HibernateSessionFactoryConfigurationTests {
-
- @Test
- public void usingLocalSessionFactoryBean() {
- saveAndRetriveEntity(LocalSessionFactoryBeanXmlConfig.class);
- }
-
- @Test
- public void usingAnnotationSessionFactoryBean() {
- saveAndRetriveEntity(AnnotationSessionFactoryBeanXmlConfig.class);
- }
-
- @Ignore @Test
- public void usingNativeHibernateConfiguration() {
- saveAndRetriveEntity(NativeHibernateConfig.class);
- }
-
- @Test
- public void usingSessionFactoryBuilder_withConfigurationCallback() {
- saveAndRetriveEntity(SessionFactoryConfig_withConfigurationCallback.class);
- }
-
- @Test
- public void usingAnnotationSessionFactoryBuilder() {
- saveAndRetriveEntity(AnnotationSessionFactoryConfig.class);
- }
-
- @Test
- public void usingAnnotationSessionFactoryBuilder_withConfigurationCallback() {
- saveAndRetriveEntity(AnnotationSessionFactoryConfig_withConfigurationCallback.class);
- }
-
- @Test
- public void usingAnnotationSessionFactoryBuilder_withPackagesToScan() {
- saveAndRetriveEntity(AnnotationSessionFactoryConfig_withPackagesToScan.class);
- }
-
- @Test
- public void usingAnnotationSessionFactoryBuilder_withAnnotatedClasses() {
- saveAndRetriveEntity(AnnotationSessionFactoryConfig_withAnnotatedClasses.class);
- }
-
-
- @Test(expected=DataAccessException.class)
- public void exceptionTranslation_withLocalSessionFactoryBean() {
- causeException(LocalSessionFactoryBeanXmlConfig.class, RepositoryConfig.class);
- }
-
- @Test(expected=DataAccessException.class)
- public void exceptionTranslation_withSessionFactoryBuilder() {
- causeException(SessionFactoryConfig_withConfigurationCallback.class,
- RepositoryConfig.class);
- }
-
- @Test
- public void usingSessionFactoryBuilder_withCustomConfigurationClass() {
- saveAndRetriveEntity(SessionFactoryConfig_withCustomConfigurationClass.class);
- }
-
- @Test(expected=IllegalStateException.class)
- public void usingSessionFactoryBuilder_withLateCustomConfigurationClass() throws Throwable {
- try {
- saveAndRetriveEntity(SessionFactoryConfig_withLateCustomConfigurationClass.class);
- } catch (BeanCreationException ex) {
- Throwable cause = ex.getRootCause();
- assertThat(cause.getMessage().startsWith("setConfigurationClass() must be called before"), is(true));
- throw cause;
- }
- }
-
-
- private void saveAndRetriveEntity(Class<?> configClass) {
- SessionFactory sessionFactory = new AnnotationConfigApplicationContext(configClass).getBean(SessionFactory.class);
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- Foo foo = new Foo();
- foo.setName("f1");
- session.save(foo);
-
- Foo f1 = (Foo) session.createQuery("from Foo where name = 'f1'").uniqueResult();
- assertThat("No foo with name='f1' found!", f1, notNullValue());
- assertThat(f1.getName(), is("f1"));
-
- tx.rollback();
- }
-
- private void causeException(Class<?>... configClasses) {
- FooRepository fooRepository = new AnnotationConfigApplicationContext(configClasses).getBean(FooRepository.class);
- fooRepository.findAll(); // will throw
- }
-
-
- @Configuration
- static class DataConfig {
- @Bean
- DataSource dataSource() {
- return new EmbeddedDatabaseBuilder()
- .setType(EmbeddedDatabaseType.HSQL)
- .build();
- }
- }
-
-
- @Configuration
- @ImportResource("org/springframework/orm/hibernate3/LocalSessionFactoryBeanXmlConfig-context.xml")
- static class LocalSessionFactoryBeanXmlConfig extends DataConfig {
- }
-
-
- interface FooRepository {
- List<Foo> findAll();
- }
-
- @Repository
- public static class HibernateFooRepository implements FooRepository {
- private final SessionFactory sessionFactory;
- public HibernateFooRepository(SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
- @Transactional
- @SuppressWarnings("unchecked")
- public List<Foo> findAll() {
- return sessionFactory.getCurrentSession().createQuery("from Bogus").list();
- }
- }
-
-
- @Configuration
- @EnableTransactionManagement
- static class RepositoryConfig {
- @Inject SessionFactory sessionFactory;
-
- @Bean
- FooRepository fooRepository() {
- return new HibernateFooRepository(sessionFactory);
- }
-
- @Bean
- PlatformTransactionManager txManager() {
- return new HibernateTransactionManager(sessionFactory);
- }
-
- @Bean
- PersistenceExceptionTranslationPostProcessor exceptionTranslationPostProcessor() {
- return new PersistenceExceptionTranslationPostProcessor();
- }
-
- @Bean
- PersistenceExceptionTranslator exceptionTranslator() {
- return new HibernateExceptionTranslator();
- }
- }
-
-
- @Configuration
- @ImportResource("org/springframework/orm/hibernate3/AnnotationSessionFactoryBeanXmlConfig-context.xml")
- static class AnnotationSessionFactoryBeanXmlConfig extends DataConfig {
- }
-
-
- @Configuration
- static class NativeHibernateConfig {
- @Bean
- SessionFactory sessionFactory() {
- org.hibernate.cfg.Configuration cfg = new AnnotationConfiguration();
- return cfg.buildSessionFactory();
- }
- }
-
-
- @Configuration
- static class AnnotationSessionFactoryConfig extends DataConfig {
- @Bean
- SessionFactory sessionFactory() throws Exception {
- return new AnnotationSessionFactoryBuilder(dataSource())
- .setSchemaUpdate(true)
- .doWithConfiguration(new HibernateConfigurationCallback<AnnotationConfiguration>() {
- public void configure(AnnotationConfiguration configuration) {
- configuration.addAnnotatedClass(Foo.class);
- }
- })
- .buildSessionFactory();
- }
- }
-
-
- @Configuration
- static class AnnotationSessionFactoryConfig_withPackagesToScan extends DataConfig {
- @Bean
- SessionFactory sessionFactory() throws Exception {
- return new AnnotationSessionFactoryBuilder(dataSource())
- .setSchemaUpdate(true)
- .setPackagesToScan(Foo.class.getPackage().getName())
- .buildSessionFactory();
- }
- }
-
- @Configuration
- static class AnnotationSessionFactoryConfig_withAnnotatedClasses extends DataConfig {
- @Bean
- SessionFactory sessionFactory() throws Exception {
- return new AnnotationSessionFactoryBuilder(dataSource())
- .setSchemaUpdate(true)
- .setAnnotatedClasses(Foo.class, Foo.class)
- .buildSessionFactory();
- }
- }
-
-
- @Configuration
- static class AnnotationSessionFactoryConfig_withConfigurationCallback extends DataConfig {
- @Bean
- SessionFactory sessionFactory() throws Exception {
- return new AnnotationSessionFactoryBuilder(dataSource())
- .setSchemaUpdate(true)
- .doWithConfiguration(new HibernateConfigurationCallback<AnnotationConfiguration>() {
- public void configure(AnnotationConfiguration configuration) throws Exception {
- configuration.addAnnotatedClass(Foo.class);
- }
- })
- .buildSessionFactory();
- }
- }
-
-
- @Configuration
- static class SessionFactoryConfig_withConfigurationCallback extends DataConfig {
- @Bean
- SessionFactory sessionFactory() throws Exception {
- return new SessionFactoryBuilder(dataSource())
- .setSchemaUpdate(true)
- .doWithConfiguration(new HibernateConfigurationCallback<org.hibernate.cfg.Configuration>() {
- public void configure(org.hibernate.cfg.Configuration configuration) throws Exception {
- configuration.addFile(new File(this.getClass().getClassLoader().getResource("org/springframework/orm/hibernate3/scannable/FooMapping.hbm.xml").toURI()));
- }
- })
- .buildSessionFactory();
- }
- }
-
-
- @Configuration
- static class SessionFactoryConfig_withCustomConfigurationClass extends DataConfig {
- @Bean
- SessionFactory sessionFactory() throws Exception {
- SessionFactoryBuilder sfb = new SessionFactoryBuilder(dataSource())
- .setSchemaUpdate(true)
- .setConfigurationClass(CustomHibernateConfiguration.class)
- .doWithConfiguration(new HibernateConfigurationCallback<org.hibernate.cfg.Configuration>() {
- public void configure(org.hibernate.cfg.Configuration configuration) throws Exception {
- configuration.addFile(new File(this.getClass().getClassLoader().getResource("org/springframework/orm/hibernate3/scannable/FooMapping.hbm.xml").toURI()));
- }
- });
- assertThat(sfb.getConfiguration(), instanceOf(CustomHibernateConfiguration.class));
- return sfb.buildSessionFactory();
- }
- }
-
-
- @Configuration
- static class SessionFactoryConfig_withLateCustomConfigurationClass extends DataConfig {
- @Bean
- SessionFactory sessionFactory() throws Exception {
- return new SessionFactoryBuilder(dataSource())
- .setSchemaUpdate(true)
- .doWithConfiguration(new HibernateConfigurationCallback<org.hibernate.cfg.Configuration>() {
- public void configure(org.hibernate.cfg.Configuration configuration) throws Exception {
- configuration.addFile(new File(this.getClass().getClassLoader().getResource("org/springframework/orm/hibernate3/scannable/FooMapping.hbm.xml").toURI()));
- }
- })
- .setConfigurationClass(CustomHibernateConfiguration.class)
- .buildSessionFactory();
- }
- }
-
-
- @SuppressWarnings("serial")
- static class CustomHibernateConfiguration extends org.hibernate.cfg.Configuration {
- }
-
-}
View
36 ...ork.integration-tests/src/test/java/org/springframework/orm/hibernate3/scannable/Foo.java
@@ -1,36 +0,0 @@
-/*
- * Copyright 2002-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.orm.hibernate3.scannable;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-@Entity
-public class Foo {
- @SuppressWarnings("unused")
- @Id private int id;
-
- private String name;
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getName() {
- return this.name;
- }
-}
View
12 ...rces/org/springframework/orm/hibernate3/AnnotationSessionFactoryBeanXmlConfig-context.xml
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
-
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
- <property name="annotatedClasses" value="org.springframework.orm.hibernate3.scannable.Foo"/>
- <property name="dataSource" ref="dataSource"/>
- <property name="schemaUpdate" value="true"/>
- </bean>
-
-</beans>
View
18 ...resources/org/springframework/orm/hibernate3/LocalSessionFactoryBeanXmlConfig-context.xml
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
-
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <!--<property name="annotatedClasses" value="org.springframework.orm.hibernate3.scannable.Foo"/>-->
- <property name="mappingLocations" value="classpath:org/springframework/orm/hibernate3/scannable/FooMapping.hbm.xml"/>
- <property name="dataSource" ref="dataSource"/>
- <property name="schemaUpdate" value="true"/>
- <property name="hibernateProperties">
- <value>
- hibernate.dialect=org.hibernate.dialect.HSQLDialect
- </value>
- </property>
- </bean>
-
-</beans>
View
12 ...-tests/src/test/resources/org/springframework/orm/hibernate3/scannable/FooMapping.hbm.xml
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-
-<hibernate-mapping>
-
- <class name="org.springframework.orm.hibernate3.scannable.Foo" table="foo">
- <id name="id" column="id" access="field"/>
- <property name="name" column="name" />
- </class>
-
-</hibernate-mapping>
View
336 ...work.orm/src/main/java/org/springframework/orm/hibernate3/AbstractSessionFactoryBean.java
@@ -0,0 +1,336 @@
+/*
+ * Copyright 2002-2010 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.orm.hibernate3;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.HibernateException;
+import org.hibernate.JDBCException;
+import org.hibernate.SessionFactory;
+
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.beans.factory.FactoryBean;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.dao.DataAccessException;
+import org.springframework.dao.support.PersistenceExceptionTranslator;
+import org.springframework.jdbc.support.SQLExceptionTranslator;
+
+/**
+ * Abstract {@link org.springframework.beans.factory.FactoryBean} that creates
+ * a Hibernate {@link org.hibernate.SessionFactory} within a Spring application
+ * context, providing general infrastructure not related to Hibernate's
+ * specific configuration API.
+ *
+ * <p>This class implements the
+ * {@link org.springframework.dao.support.PersistenceExceptionTranslator}
+ * interface, as autodetected by Spring's
+ * {@link org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor},
+ * for AOP-based translation of native exceptions to Spring DataAccessExceptions.
+ * Hence, the presence of e.g. LocalSessionFactoryBean automatically enables
+ * a PersistenceExceptionTranslationPostProcessor to translate Hibernate exceptions.
+ *
+ * <p>This class mainly serves as common base class for {@link LocalSessionFactoryBean}.
+ * For details on typical SessionFactory setup, see the LocalSessionFactoryBean javadoc.
+ *
+ * @author Juergen Hoeller
+ * @since 2.0
+ * @see #setExposeTransactionAwareSessionFactory
+ * @see org.hibernate.SessionFactory#getCurrentSession()
+ * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
+ */
+public abstract class AbstractSessionFactoryBean
+ implements FactoryBean<SessionFactory>, InitializingBean, DisposableBean, PersistenceExceptionTranslator {
+
+ /** Logger available to subclasses */
+ protected final Log logger = LogFactory.getLog(getClass());
+
+ private DataSource dataSource;
+
+ private boolean useTransactionAwareDataSource = false;
+
+ private boolean exposeTransactionAwareSessionFactory = true;
+
+ private SQLExceptionTranslator jdbcExceptionTranslator;
+
+ private SessionFactory sessionFactory;
+
+
+ /**
+ * Set the DataSource to be used by the SessionFactory.
+ * If set, this will override corresponding settings in Hibernate properties.
+ * <p>If this is set, the Hibernate settings should not define
+ * a connection provider to avoid meaningless double configuration.
+ * <p>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.
+ * <p>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 #setUseTransactionAwareDataSource
+ * @see HibernateTransactionManager
+ * @see org.springframework.transaction.jta.JtaTransactionManager
+ * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
+ */
+ public void setDataSource(DataSource dataSource) {
+ this.dataSource = dataSource;
+ }
+
+ /**
+ * Return the DataSource to be used by the SessionFactory.
+ */
+ public DataSource getDataSource() {
+ return this.dataSource;
+ }
+
+ /**
+ * 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.
+ * <p>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.
+ * <p>If you switch this flag to "true", Spring's Hibernate access will be able to
+ * <i>participate in JDBC-based transactions managed outside of Hibernate</i>
+ * (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.
+ * <p>A further benefit of this option is that <i>plain Sessions opened directly
+ * via the SessionFactory</i>, outside of Spring's Hibernate support, will still
+ * participate in active Spring-managed transactions. However, consider using
+ * Hibernate's <code>getCurrentSession()</code> method instead (see javadoc of
+ * "exposeTransactionAwareSessionFactory" property).
+ * <p><b>WARNING:</b> 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".
+ * <p>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".
+ * Otherwise, the ConnectionProvider used underneath will vote against aggressive
+ * release and thus silently switch to release mode "after_transaction".
+ * @see #setDataSource
+ * @see #setExposeTransactionAwareSessionFactory
+ * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
+ * @see org.springframework.jdbc.datasource.DataSourceTransactionManager
+ * @see org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
+ * @see org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor
+ * @see HibernateTransactionManager
+ * @see org.springframework.transaction.jta.JtaTransactionManager
+ */
+ public void setUseTransactionAwareDataSource(boolean useTransactionAwareDataSource) {
+ this.useTransactionAwareDataSource = useTransactionAwareDataSource;
+ }
+
+ /**
+ * Return whether to use a transaction-aware DataSource for the SessionFactory.
+ */
+ protected boolean isUseTransactionAwareDataSource() {
+ return this.useTransactionAwareDataSource;
+ }
+
+ /**
+ * Set whether to expose a transaction-aware current Session from the
+ * SessionFactory's <code>getCurrentSession()</code> method, returning the
+ * Session that's associated with the current Spring-managed transaction, if any.
+ * <p>Default is "true", letting data access code work with the plain
+ * Hibernate SessionFactory and its <code>getCurrentSession()</code> 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, <code>getCurrentSession()</code> will also seamlessly work with
+ * a request-scoped Session managed by OpenSessionInViewFilter/Interceptor.
+ * <p>Turn this flag off to expose the plain Hibernate SessionFactory with
+ * Hibernate's default <code>getCurrentSession()</code> behavior, supporting
+ * plain JTA synchronization only. Alternatively, simply override the
+ * corresponding Hibernate property "hibernate.current_session_context_class".
+ * @see SpringSessionContext
+ * @see org.hibernate.SessionFactory#getCurrentSession()
+ * @see org.springframework.transaction.jta.JtaTransactionManager
+ * @see HibernateTransactionManager
+ * @see org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
+ * @see org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor
+ */
+ public void setExposeTransactionAwareSessionFactory(boolean exposeTransactionAwareSessionFactory) {
+ this.exposeTransactionAwareSessionFactory = exposeTransactionAwareSessionFactory;
+ }
+
+ /**
+ * Return whether to expose a transaction-aware proxy for the SessionFactory.
+ */
+ protected boolean isExposeTransactionAwareSessionFactory() {
+ return this.exposeTransactionAwareSessionFactory;
+ }
+
+ /**
+ * Set the JDBC exception translator for the SessionFactory,
+ * exposed via the PersistenceExceptionTranslator interface.
+ * <p>Applied to any SQLException root cause of a Hibernate JDBCException,
+ * overriding Hibernate's default SQLException translation (which is
+ * based on Hibernate's Dialect for a specific target database).
+ * @param jdbcExceptionTranslator the exception translator
+ * @see java.sql.SQLException
+ * @see org.hibernate.JDBCException
+ * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator
+ * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator
+ * @see org.springframework.dao.support.PersistenceExceptionTranslator
+ */
+ public void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator) {
+ this.jdbcExceptionTranslator = jdbcExceptionTranslator;
+ }
+
+
+ /**
+ * Build and expose the SessionFactory.
+ * @see #buildSessionFactory()
+ * @see #wrapSessionFactoryIfNecessary
+ */
+ public void afterPropertiesSet() throws Exception {
+ SessionFactory rawSf = buildSessionFactory();
+ this.sessionFactory = wrapSessionFactoryIfNecessary(rawSf);
+ afterSessionFactoryCreation();
+ }
+
+ /**
+ * Wrap the given SessionFactory with a proxy, if demanded.
+ * <p>The default implementation simply returns the given SessionFactory as-is.
+ * Subclasses may override this to implement transaction awareness through
+ * a SessionFactory proxy, for example.
+ * @param rawSf the raw SessionFactory as built by {@link #buildSessionFactory()}
+ * @return the SessionFactory reference to expose
+ * @see #buildSessionFactory()
+ */
+ protected SessionFactory wrapSessionFactoryIfNecessary(SessionFactory rawSf) {
+ return rawSf;
+ }
+
+ /**
+ * Return the exposed SessionFactory.
+ * Will throw an exception if not initialized yet.
+ * @return the SessionFactory (never <code>null</code>)
+ * @throws IllegalStateException if the SessionFactory has not been initialized yet
+ */
+ protected final SessionFactory getSessionFactory() {
+ if (this.sessionFactory == null) {
+ throw new IllegalStateException("SessionFactory not initialized yet");
+ }
+ return this.sessionFactory;
+ }
+
+ /**
+ * Close the SessionFactory on bean factory shutdown.
+ */
+ public void destroy() throws HibernateException {
+ logger.info("Closing Hibernate SessionFactory");
+ try {
+ beforeSessionFactoryDestruction();
+ }
+ finally {
+ this.sessionFactory.close();
+ }
+ }
+
+
+ /**
+ * Return the singleton SessionFactory.
+ */
+ public SessionFactory getObject() {
+ return this.sessionFactory;
+ }
+
+ public Class<? extends SessionFactory> getObjectType() {
+ return (this.sessionFactory != null ? this.sessionFactory.getClass() : SessionFactory.class);
+ }
+
+ public boolean isSingleton() {
+ return true;
+ }
+
+
+ /**
+ * Implementation of the PersistenceExceptionTranslator interface,
+ * as autodetected by Spring's PersistenceExceptionTranslationPostProcessor.
+ * <p>Converts the exception if it is a HibernateException;
+ * else returns <code>null</code> to indicate an unknown exception.
+ * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
+ * @see #convertHibernateAccessException
+ */
+ public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
+ if (ex instanceof HibernateException) {
+ return convertHibernateAccessException((HibernateException) ex);
+ }
+ return null;
+ }
+
+ /**
+ * Convert the given HibernateException to an appropriate exception from the
+ * <code>org.springframework.dao</code> hierarchy.
+ * <p>Will automatically apply a specified SQLExceptionTranslator to a
+ * Hibernate JDBCException, else rely on Hibernate's default translation.
+ * @param ex HibernateException that occured
+ * @return a corresponding DataAccessException
+ * @see SessionFactoryUtils#convertHibernateAccessException
+ * @see #setJdbcExceptionTranslator
+ */
+ protected DataAccessException convertHibernateAccessException(HibernateException ex) {
+ if (this.jdbcExceptionTranslator != null && ex instanceof JDBCException) {
+ JDBCException jdbcEx = (JDBCException) ex;
+ return this.jdbcExceptionTranslator.translate(
+ "Hibernate operation: " + jdbcEx.getMessage(), jdbcEx.getSQL(), jdbcEx.getSQLException());
+ }
+ return SessionFactoryUtils.convertHibernateAccessException(ex);
+ }
+
+
+ /**
+ * Build the underlying Hibernate SessionFactory.
+ * @return 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
+ */
+ protected abstract SessionFactory buildSessionFactory() throws Exception;
+
+ /**
+ * Hook that allows post-processing after the SessionFactory has been
+ * successfully created. The SessionFactory is already available through
+ * <code>getSessionFactory()</code> at this point.
+ * <p>This implementation is empty.
+ * @throws Exception in case of initialization failure
+ * @see #getSessionFactory()
+ */
+ protected void afterSessionFactoryCreation() throws Exception {
+ }
+
+ /**
+ * Hook that allows shutdown processing before the SessionFactory
+ * will be closed. The SessionFactory is still available through
+ * <code>getSessionFactory()</code> at this point.
+ * <p>This implementation is empty.
+ * @see #getSessionFactory()
+ */
+ protected void beforeSessionFactoryDestruction() {
+ }
+
+}
View
37 ...ork.orm/src/main/java/org/springframework/orm/hibernate3/FilterDefinitionFactoryBean.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,25 +37,24 @@
* definition, as the list element for the "filterDefinitions" bean property.
* For example:
*
- * <pre class="code">
- * {@code
- * <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
+ * <pre>
+ * &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt;
* ...
- * <property name="filterDefinitions">
- * <list>
- * <bean class="org.springframework.orm.hibernate3.FilterDefinitionFactoryBean">
- * <property name="filterName" value="myFilter"/>
- * <property name="parameterTypes">
- * <map>
- * <entry key="myParam" value="string"/>
- * <entry key="myOtherParam" value="long"/>
- * </map>
- * </property>
- * </bean>
- * </list>
- * </property>
+ * &lt;property name="filterDefinitions"&gt;
+ * &lt;list&gt;
+ * &lt;bean class="org.springframework.orm.hibernate3.FilterDefinitionFactoryBean"&gt;
+ * &lt;property name="filterName" value="myFilter"/&gt;
+ * &lt;property name="parameterTypes"&gt;
+ * &lt;map&gt;
+ * &lt;entry key="myParam" value="string"/&gt;
+ * &lt;entry key="myOtherParam" value="long"/&gt;
+ * &lt;/map&gt;
+ * &lt;/property&gt;
+ * &lt;/bean&gt;
+ * &lt;/list&gt;
+ * &lt;/property&gt;
* ...
- * </bean>}</pre>
+ * &lt;/bean&gt;</pre>
*
* Alternatively, specify a bean id (or name) attribute for the inner bean,
* instead of the "filterName" property.
@@ -74,7 +73,7 @@
static {
// Hibernate 3.6 TypeResolver class available?
try {
- Class<?> trClass = FilterDefinitionFactoryBean.class.getClassLoader().loadClass(
+ Class trClass = FilterDefinitionFactoryBean.class.getClassLoader().loadClass(
"org.hibernate.type.TypeResolver");
heuristicTypeMethod = trClass.getMethod("heuristicType", String.class);
typeResolver = trClass.newInstance();
View
17 ...ringframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateAccessor.java
@@ -181,13 +181,12 @@ public void setEntityInterceptorBeanName(String entityInterceptorBeanName) {
* property values before writing to and reading from the database.
* Will get applied to any <b>new</b> Session created by this object.
* <p>Such an interceptor can either be set at the SessionFactory level,
- * i.e. on SessionFactoryBuilder/LocalSessionFactoryBean, 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.
+ * 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 #setEntityInterceptorBeanName
- * @see SessionFactoryBuilder#setEntityInterceptor
+ * @see LocalSessionFactoryBean#setEntityInterceptor
* @see HibernateTransactionManager#setEntityInterceptor
*/
public void setEntityInterceptor(Interceptor entityInterceptor) {
@@ -209,7 +208,7 @@ public Interceptor getEntityInterceptor() throws IllegalStateException, BeansExc
if (this.beanFactory == null) {
throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set");
}
- return this.beanFactory.getBean((String) this.entityInterceptor, Interceptor.class);
+ return (Interceptor) this.beanFactory.getBean((String) this.entityInterceptor, Interceptor.class);
}
return (Interceptor) this.entityInterceptor;
}
@@ -273,7 +272,7 @@ public int getFlushMode() {
* Sessions (for example, within a transaction).
* @see #enableFilters(org.hibernate.Session)
* @see org.hibernate.Session#enableFilter(String)
- * @see SessionFactoryBuilder#setFilterDefinitions
+ * @see LocalSessionFactoryBean#setFilterDefinitions
*/
public void setFilterName(String filter) {
this.filterNames = new String[] {filter};
@@ -288,7 +287,7 @@ public void setFilterName(String filter) {
* Sessions (for example, within a transaction).
* @see #enableFilters(org.hibernate.Session)
* @see org.hibernate.Session#enableFilter(String)
- * @see SessionFactoryBuilder#setFilterDefinitions
+ * @see LocalSessionFactoryBean#setFilterDefinitions
*/
public void setFilterNames(String[] filterNames) {
this.filterNames = filterNames;
View
41 ....orm/src/main/java/org/springframework/orm/hibernate3/HibernateConfigurationCallback.java
@@ -1,41 +0,0 @@
-/*
- * Copyright 2002-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.orm.hibernate3;
-
-import org.hibernate.cfg.Configuration;
-
-/**
- * Callback for use in conjunction with {@link SessionFactoryBuilderSupport#doWithConfiguration}.
- *
- * @author Chris Beams
- * @since 3.1
- * @see SessionFactoryBuilderSupport#doWithConfiguration
- * @see SessionFactoryBuilder
- * @see org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBuilder
- */
-public interface HibernateConfigurationCallback<C extends Configuration> {
-
- /**
- * Configure the given Hibernate {@code Configuration type}. Note that methods
- * only setter methods should be called, and methods such as
- * {@link Configuration#buildSessionFactory()} should be avoided.
- * @throws Exception to propagate any exception thrown by
- * {@code Configuration} methods
- */
- void configure(C configuration) throws Exception;
-
-}
View
13 ...ringframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTemplate.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,6 +40,7 @@
import org.hibernate.criterion.Example;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.event.EventSource;
+
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
@@ -76,10 +77,10 @@
* management, not participating in a custom Hibernate CurrentSessionContext
* unless you explicitly switch {@link #setAllowCreate "allowCreate"} to "false".</b>
*
- * <p>Using a {@link SessionFactoryBuilder} is the preferred way of obtaining a
- * reference to a specific Hibernate SessionFactory, at least in a non-EJB
- * environment. The Spring application context will manage its lifecycle,
- * initializing and shutting down the factory as part of the application.
+ * <p>{@link LocalSessionFactoryBean} is the preferred way of obtaining a reference
+ * to a specific Hibernate SessionFactory, at least in a non-EJB environment.
+ * The Spring application context will manage its lifecycle, initializing and
+ * shutting down the factory as part of the application.
*
* <p>Note that operations that return an Iterator (i.e. <code>iterate</code>)
* are supposed to be used within Spring-driven or JTA-driven transactions
@@ -98,7 +99,7 @@
* @see #setSessionFactory
* @see HibernateCallback
* @see org.hibernate.Session
- * @see SessionFactoryBuilder
+ * @see LocalSessionFactoryBean
* @see HibernateTransactionManager
* @see org.springframework.transaction.jta.JtaTransactionManager
* @see org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
View
26 ...ork.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java
@@ -80,9 +80,8 @@
* this instance needs to be aware of the DataSource ({@link #setDataSource}).
* The given DataSource should obviously match the one used by the given
* SessionFactory. To achieve this, configure both to the same JNDI DataSource,
- * or preferably create the SessionFactory with {@link SessionFactoryBuilder} /
- * {@link LocalSessionFactoryBean} and a local DataSource (which will be
- * autodetected by this transaction manager).
+ * or preferably create the SessionFactory with {@link LocalSessionFactoryBean} and
+ * a local DataSource (which will be autodetected by this transaction manager).
*
* <p>JTA (usually through {@link org.springframework.transaction.jta.JtaTransactionManager})
* is necessary for accessing multiple transactional resources within the same
@@ -117,7 +116,6 @@
* @since 1.2
* @see #setSessionFactory
* @see #setDataSource
- * @see SessionFactoryBuilder
* @see LocalSessionFactoryBean
* @see SessionFactoryUtils#getSession
* @see SessionFactoryUtils#applyTransactionTimeout
@@ -131,7 +129,6 @@
* @see org.springframework.jdbc.datasource.DataSourceTransactionManager
* @see org.springframework.transaction.jta.JtaTransactionManager
*/
-@SuppressWarnings("serial")
public class HibernateTransactionManager extends AbstractPlatformTransactionManager
implements ResourceTransactionManager, BeanFactoryAware, InitializingBean {
@@ -197,7 +194,7 @@ public SessionFactory getSessionFactory() {
* The DataSource should match the one used by the Hibernate SessionFactory:
* for example, you could specify the same JNDI DataSource for both.
* <p>If the SessionFactory was configured with LocalDataSourceConnectionProvider,
- * i.e. by Spring's SessionFactoryBuilder with a specified "dataSource",
+ * i.e. by Spring's LocalSessionFactoryBean with a specified "dataSource",
* the DataSource will be auto-detected: You can still explictly specify the
* DataSource, but you don't need to in this case.
* <p>A transactional JDBC Connection for this DataSource will be provided to
@@ -211,7 +208,7 @@ public SessionFactory getSessionFactory() {
* unwrapped to extract its target DataSource.
* @see #setAutodetectDataSource
* @see LocalDataSourceConnectionProvider
- * @see SessionFactoryBuilder#setDataSource
+ * @see LocalSessionFactoryBean#setDataSource
* @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
* @see org.springframework.jdbc.datasource.DataSourceUtils
* @see org.springframework.jdbc.core.JdbcTemplate
@@ -237,11 +234,11 @@ public DataSource getDataSource() {
/**
* Set whether to autodetect a JDBC DataSource used by the Hibernate SessionFactory,
- * if set via SessionFactoryBuilder's <code>setDataSource</code>. Default is "true".
+ * if set via LocalSessionFactoryBean's <code>setDataSource</code>. Default is "true".
* <p>Can be turned off to deliberately ignore an available DataSource, in order
* to not expose Hibernate transactions as JDBC transactions for that DataSource.
* @see #setDataSource
- * @see SessionFactoryBuilder#setDataSource
+ * @see LocalSessionFactoryBean#setDataSource
*/
public void setAutodetectDataSource(boolean autodetectDataSource) {
this.autodetectDataSource = autodetectDataSource;
@@ -332,11 +329,11 @@ public void setEntityInterceptorBeanName(String entityInterceptorBeanName) {
* property values before writing to and reading from the database.
* Will get applied to any new Session created by this transaction manager.
* <p>Such an interceptor can either be set at the SessionFactory level,
- * i.e. on SessionFactoryBuilder, or at the Session level, i.e. on
+ * i.e. on LocalSessionFactoryBean, or at the Session level, i.e. on
* HibernateTemplate, HibernateInterceptor, and HibernateTransactionManager.
- * It's preferable to set it on SessionFactoryBuilder or HibernateTransactionManager
+ * It's preferable to set it on LocalSessionFactoryBean or HibernateTransactionManager
* to avoid repeated configuration and guarantee consistent behavior in transactions.
- * @see SessionFactoryBuilder#setEntityInterceptor
+ * @see LocalSessionFactoryBean#setEntityInterceptor
* @see HibernateTemplate#setEntityInterceptor
* @see HibernateInterceptor#setEntityInterceptor
*/
@@ -507,7 +504,6 @@ protected void doBegin(Object transaction, TransactionDefinition definition) {
logger.debug(
"Preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]");
}
- @SuppressWarnings("deprecation")
Connection con = session.connection();
Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
txObject.setPreviousIsolationLevel(previousIsolationLevel);
@@ -520,7 +516,7 @@ protected void doBegin(Object transaction, TransactionDefinition definition) {
"HibernateTransactionManager is not allowed to support custom isolation levels: " +
"make sure that its 'prepareConnection' flag is on (the default) and that the " +
"Hibernate connection release mode is set to 'on_close' (SpringTransactionFactory's default). " +
- "Make sure that your SessionFactoryBuilder actually uses SpringTransactionFactory: Your " +
+ "Make sure that your LocalSessionFactoryBean actually uses SpringTransactionFactory: Your " +
"Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!");
}
if (logger.isDebugEnabled()) {
@@ -564,7 +560,6 @@ protected void doBegin(Object transaction, TransactionDefinition definition) {
// Register the Hibernate Session's JDBC Connection for the DataSource, if set.
if (getDataSource() != null) {
- @SuppressWarnings("deprecation")
Connection con = session.connection();
ConnectionHolder conHolder = new ConnectionHolder(con);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
@@ -726,7 +721,6 @@ protected void doCleanupAfterCompletion(Object transaction) {
// the isolation level and/or read-only flag of the JDBC Connection here.
// Else, we need to rely on the connection pool to perform proper cleanup.
try {
- @SuppressWarnings("deprecation")
Connection con = session.connection();
DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
}
View
11 ...amework.orm/src/main/java/org/springframework/orm/hibernate3/LocalCacheProviderProxy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,23 +28,16 @@
* "cacheProvider" property.
*
* @author Juergen Hoeller
- * @author Chris Beams
* @since 2.5.1
* @see LocalSessionFactoryBean#setCacheProvider
- * @see LocalRegionFactoryProxy
- * @deprecated as of Spring 3.1 to reflect the deprecation of the
- * CacheProvider SPI in Hibernate 3.3. Favor the new
- * {@link org.hibernate.cache.RegionFactory} SPI and Spring's
- * {@link LocalRegionFactoryProxy} support.
*/
-@Deprecated
public class LocalCacheProviderProxy implements CacheProvider {
private final CacheProvider cacheProvider;
public LocalCacheProviderProxy() {
- CacheProvider cp = SessionFactoryBeanDelegate.getConfigTimeCacheProvider();
+ CacheProvider cp = LocalSessionFactoryBean.getConfigTimeCacheProvider();
// absolutely needs thread-bound CacheProvider to initialize
if (cp == null) {
throw new IllegalStateException("No Hibernate CacheProvider found - " +
View
15 ...m/src/main/java/org/springframework/orm/hibernate3/LocalDataSourceConnectionProvider.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
-
import javax.sql.DataSource;
import org.hibernate.HibernateException;
@@ -29,12 +28,12 @@
/**
* Hibernate connection provider for local DataSource instances
* in an application context. This provider will be used if
- * SessionFactoryBuilder's "dataSource" property is set
+ * LocalSessionFactoryBean's "dataSource" property is set
* without a Hibernate TransactionManagerLookup.
*
* @author Juergen Hoeller
* @since 1.2
- * @see SessionFactoryBuilder#setDataSource
+ * @see LocalSessionFactoryBean#setDataSource
*/
public class LocalDataSourceConnectionProvider implements ConnectionProvider {
@@ -44,11 +43,11 @@
public void configure(Properties props) throws HibernateException {
- this.dataSource = SessionFactoryBuilderSupport.getConfigTimeDataSource();
+ this.dataSource = LocalSessionFactoryBean.getConfigTimeDataSource();
// absolutely needs thread-bound DataSource to initialize
if (this.dataSource == null) {
throw new HibernateException("No local DataSource found for configuration - " +
- "'dataSource' property must be set on SessionFactoryBuilder");
+ "'dataSource' property must be set on LocalSessionFactoryBean");
}
this.dataSourceToUse = getDataSourceToUse(this.dataSource);
}
@@ -57,10 +56,10 @@ public void configure(Properties props) throws HibernateException {
* Return the DataSource to use for retrieving Connections.
* <p>This implementation returns the passed-in DataSource as-is.
* @param originalDataSource the DataSource as configured by the user
- * on SessionFactoryBuilder
+ * on LocalSessionFactoryBean
* @return the DataSource to actually retrieve Connections from
* (potentially wrapped)
- * @see SessionFactoryBuilder#setDataSource
+ * @see LocalSessionFactoryBean#setDataSource
*/
protected DataSource getDataSourceToUse(DataSource originalDataSource) {
return originalDataSource;
View
4 ...rc/main/java/org/springframework/orm/hibernate3/LocalJtaDataSourceConnectionProvider.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,7 @@
/**
* Subclass of LocalDataSourceConnectionProvider that will be used
- * if SessionFactoryBean's "dataSource" property is set
+ * if LocalSessionFactoryBean's "dataSource" property is set
* in combination with a Hibernate TransactionManagerLookup.
*
* @author Juergen Hoeller
View
10 ...amework.orm/src/main/java/org/springframework/orm/hibernate3/LocalRegionFactoryProxy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@
/**
* Proxy for a Hibernate RegionFactory, delegating to a Spring-managed
- * RegionFactory instance, determined by SessionFactoryBuilder's
+ * RegionFactory instance, determined by LocalSessionFactoryBean's
* "cacheRegionFactory" property.
*
* <p>Compatible with Hibernate 3.3 as well as Hibernate 3.5's version
@@ -41,7 +41,7 @@
*
* @author Juergen Hoeller
* @since 3.0
- * @see SessionFactoryBuilder#setCacheRegionFactory
+ * @see LocalSessionFactoryBean#setCacheRegionFactory
*/
public class LocalRegionFactoryProxy implements RegionFactory {
@@ -52,11 +52,11 @@
* Standard constructor.
*/
public LocalRegionFactoryProxy() {
- RegionFactory rf = (RegionFactory) SessionFactoryBuilderSupport.getConfigTimeRegionFactory();
+ RegionFactory rf = (RegionFactory) LocalSessionFactoryBean.getConfigTimeRegionFactory();
// absolutely needs thread-bound RegionFactory to initialize
if (rf == null) {
throw new IllegalStateException("No Hibernate RegionFactory found - " +
- "'cacheRegionFactory' property must be set on SessionFactoryBuilder");
+ "'cacheRegionFactory' property must be set on LocalSessionFactoryBean");
}
this.regionFactory = rf;
}
View
1,124 ...amework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,125 +16,1109 @@
package org.springframework.orm.hibernate3;
-import org.hibernate.HibernateException;
+import java.io.File;
+import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.Map;
+import java.util.Properties;
+import javax.sql.DataSource;
+import javax.transaction.TransactionManager;
+import org.hibernate.HibernateException;
+import org.hibernate.Interceptor;
+import org.hibernate.Session;
import org.hibernate.SessionFactory;
+import org.hibernate.cache.CacheProvider;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.cfg.NamingStrategy;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.engine.FilterDefinition;
+import org.hibernate.event.EventListeners;
+import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
+import org.hibernate.transaction.JTATransactionFactory;
+
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.BeanClassLoaderAware;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessException;
-import org.springframework.jdbc.support.SQLExceptionTranslator;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.jdbc.support.JdbcUtils;
+import org.springframework.jdbc.support.lob.LobHandler;
+import org.springframework.util.ClassUtils;
+import org.springframework.util.ReflectionUtils;
+import org.springframework.util.StringUtils;
/**
- * Subclass of {@link SessionFactoryBuilder} adhering to Spring's
- * {@link org.springframework.beans.factory.FactoryBean FactoryBean} contract,
- * making it suitable for use in XML configuration.
+ * {@link org.springframework.beans.factory.FactoryBean} that creates a
+ * Hibernate {@link org.hibernate.SessionFactory}. This is the usual way to
+ * set up a shared Hibernate SessionFactory in a Spring application context;
+ * the SessionFactory can then be passed to Hibernate-based DAOs via
+ * dependency injection.
+ *
+ * <p>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.
*
- * <p>A typical {@code LocalSessionFactoryBean} bean definition:
+ * <p>This SessionFactory handling strategy is appropriate for most types of
+ * applications, from Hibernate-only single database apps to ones that need
+ * distributed transactions. Either {@link HibernateTransactionManager} or
+ * {@link org.springframework.transaction.jta.JtaTransactionManager} can be
+ * used for transaction demarcation, with the latter only necessary for
+ * transactions which span multiple databases.
*
- * <pre class="code">
- * {@code
- * <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- * <property name="dataSource" ref="dataSource"/>
- * <property name="mappingLocations" value="classpath:com/foo/*.hbm.xml"/>
- * </bean>}</pre>
+ * <p>This factory bean will by default expose a transaction-aware SessionFactory
+ * proxy, letting data access code work with the plain Hibernate SessionFactory
+ * and its <code>getCurrentSession()</code> 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,
+ * <code>getCurrentSession()</code> will also seamlessly work with
+ * a request-scoped Session managed by
+ * {@link org.springframework.orm.hibernate3.support.OpenSessionInViewFilter} /
+ * {@link org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor}.
*
- * <p>Implements the
- * {@link org.springframework.dao.support.PersistenceExceptionTranslator
- * PersistenceExceptionTranslator} interface, as autodetected by Spring's {@link
- * org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
- * PersistenceExceptionTranslationPostProcessor}, for AOP-based translation of
- * native Hibernate exceptions to Spring's {@link DataAccessException} hierarchy.
- * Hence, the presence of an {@code LocalSessionFactoryBean} automatically
- * enables a {@code PersistenceExceptionTranslationPostProcessor} to translate
- * Hibernate exceptions.
+ * <p><b>Requires Hibernate 3.2 or later; tested with 3.3, 3.5 and 3.6.</b>
+ * 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).
*
* @author Juergen Hoeller
- * @author Chris Beams
* @since 1.2
- * @see SessionFactoryBuilderSupport
- * @see SessionFactoryBeanOperations
- * @see org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
+ * @see HibernateTemplate#setSessionFactory
+ * @see HibernateTransactionManager#setSessionFactory
+ * @see #setExposeTransactionAwareSessionFactory
+ * @see #setJtaTransactionManager
+ * @see org.hibernate.SessionFactory#getCurrentSession()
+ * @see HibernateTransactionManager
*/
-public class LocalSessionFactoryBean extends SessionFactoryBuilder implements SessionFactoryBeanOperations {
+public class LocalSessionFactoryBean extends AbstractSessionFactoryBean implements BeanClassLoaderAware {
+
+ private static final ThreadLocal<DataSource> configTimeDataSourceHolder =
+ new ThreadLocal<DataSource>();
+
+ private static final ThreadLocal<TransactionManager> configTimeTransactionManagerHolder =
+ new ThreadLocal<TransactionManager>();
+
+ private static final ThreadLocal<Object> configTimeRegionFactoryHolder =
+ new ThreadLocal<Object>();
+
+ private static final ThreadLocal<CacheProvider> configTimeCacheProviderHolder =
+ new ThreadLocal<CacheProvider>();
+
+ private static final ThreadLocal<LobHandler> configTimeLobHandlerHolder =
+ new ThreadLocal<LobHandler>();
+
+ /**
+ * Return the DataSource for the currently configured Hibernate SessionFactory,
+ * to be used by LocalDataSourceConnectionProvoder.
+ * <p>This instance will be set before initialization of the corresponding
+ * SessionFactory, and reset immediately afterwards. It is thus only available
+ * during configuration.
+ * @see #setDataSource
+ * @see LocalDataSourceConnectionProvider
+ */
+ public static DataSource getConfigTimeDataSource() {
+ return configTimeDataSourceHolder.get();
+ }
+
+ /**
+ * Return the JTA TransactionManager for the currently configured Hibernate
+ * SessionFactory, to be used by LocalTransactionManagerLookup.
+ * <p>This instance will be set before initialization of the corresponding
+ * SessionFactory, and reset immediately afterwards. It is thus only available
+ * during configuration.
+ * @see #setJtaTransactionManager
+ * @see LocalTransactionManagerLookup
+ */
+ public static TransactionManager getConfigTimeTransactionManager() {
+ return configTimeTransactionManagerHolder.get();
+ }
+
+ /**
+ * Return the RegionFactory for the currently configured Hibernate SessionFactory,
+ * to be used by LocalRegionFactoryProxy.
+ * <p>This instance will be set before initialization of the corresponding
+ * SessionFactory, and reset immediately afterwards. It is thus only available
+ * during configuration.
+ * @see #setCacheRegionFactory
+ */
+ static Object getConfigTimeRegionFactory() {
+ return configTimeRegionFactoryHolder.get();
+ }
+
+ /**
+ * Return the CacheProvider for the currently configured Hibernate SessionFactory,
+ * to be used by LocalCacheProviderProxy.
+ * <p>This instance will be set before initialization of the corresponding
+ * SessionFactory, and reset immediately afterwards. It is thus only available
+ * during configuration.
+ * @see #setCacheProvider
+ */
+ public static CacheProvider getConfigTimeCacheProvider() {
+ return configTimeCacheProviderHolder.get();
+ }
+
+ /**
+ * Return the LobHandler for the currently configured Hibernate SessionFactory,
+ * to be used by UserType implementations like ClobStringType.
+ * <p>This instance will be set before initialization of the corresponding
+ * SessionFactory, and reset immediately afterwards. It is thus only available
+ * during configuration.
+ * @see #setLobHandler
+ * @see org.springframework.orm.hibernate3.support.ClobStringType
+ * @see org.springframework.orm.hibernate3.support.BlobByteArrayType
+ * @see org.springframework.orm.hibernate3.support.BlobSerializableType
+ */
+ public static LobHandler getConfigTimeLobHandler() {
+ return configTimeLobHandlerHolder.get();
+ }
+
+
+ private Class<? extends Configuration> configurationClass = Configuration.class;
+
+ private Resource[] configLocations;
+
+ private String[] mappingResources;
+
+ private Resource[] mappingLocations;
+
+ private Resource[] cacheableMappingLocations;
+
+ private Resource[] mappingJarLocations;
+
+ private Resource[] mappingDirectoryLocations;
+
+ private Properties hibernateProperties;
+
+ private TransactionManager jtaTransactionManager;
+
+ private Object cacheRegionFactory;
+
+ private CacheProvider cacheProvider;
+
+ private LobHandler lobHandler;
+
+ private Interceptor entityInterceptor;
+
+ private NamingStrategy namingStrategy;
+
+ private TypeDefinitionBean[] typeDefinitions;
+
+ private FilterDefinition[] filterDefinitions;
+
+ private Properties entityCacheStrategies;
+
+ private Properties collectionCacheStrategies;
+
+ private Map<String, Object> eventListeners;
+
+ private boolean schemaUpdate = false;
+
+ private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
+
+ private Configuration configuration;
+
+
+ /**
+ * Specify the Hibernate Configuration class to use.
+ * Default is "org.hibernate.cfg.Configuration"; any subclass of
+ * this default Hibernate Configuration class can be specified.
+ * <p>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).
+ * <p>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 #setConfigLocation
+ * @see org.hibernate.cfg.Configuration
+ * @see org.hibernate.cfg.AnnotationConfiguration
+ */
+ @SuppressWarnings("unchecked")
+ public void setConfigurationClass(Class<?> configurationClass) {
+ if (configurationClass == null || !Configuration.class.isAssignableFrom(configurationClass)) {
+ throw new IllegalArgumentException(
+ "'configurationClass' must be assignable to [org.hibernate.cfg.Configuration]");
+ }
+ this.configurationClass = (Class<? extends Configuration>) configurationClass;
+ }
+
+ /**
+ * Set the location of a single Hibernate XML config file, for example as
+ * classpath resource "classpath:hibernate.cfg.xml".
+ * <p>Note: Can be omitted when all necessary properties and mapping
+ * resources are specified locally via this bean.
+ * @see org.hibernate.cfg.Configuration#configure(java.net.URL)
+ */
+ public void setConfigLocation(Resource configLocation) {
+ this.configLocations = new Resource[] {configLocation};
+ }
+
+ /**
+ * Set the locations of multiple Hibernate XML config files, for example as
+ * classpath resources "classpath:hibernate.cfg.xml,classpath:extension.cfg.xml".
+ * <p>Note: Can be omitted when all necessary properties and mapping
+ * resources are specified locally via this bean.
+ * @see org.hibernate.cfg.Configuration#configure(java.net.URL)
+ */
+ public void setConfigLocations(Resource[] configLocations) {
+ this.configLocations = configLocations;
+ }
+
+ /**
+ * 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.
+ * <p>Can be used to add to mappings from a Hibernate XML config file,
+ * or to specify all mappings locally.
+ * @see #setMappingLocations
+ * @see org.hibernate.cfg.Configuration#addResource
+ */
+ public void setMappingResources(String[] mappingResources) {
+ this.mappingResources = mappingResources;
+ }
+
+ /**
+ * 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.
+ * <p>Can be used to add to mappings from a Hibernate XML config file,
+ * or to specify all mappings locally.
+ * @see org.hibernate.cfg.Configuration#addInputStream
+ */
+ public void setMappingLocations(Resource[] mappingLocations) {
+ this.mappingLocations = mappingLocations;
+ }
+
+ /**
+ * 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.
+ * <p>Can be used to add to mappings from a Hibernate XML config file,
+ * or to specify all mappings locally.
+ * @see org.hibernate.cfg.Configuration#addCacheableFile(java.io.File)
+ */
+ public void setCacheableMappingLocations(Resource[] cacheableMappingLocations) {
+ this.cacheableMappingLocations = cacheableMappingLocations;
+ }
+
+ /**
+ * Set locations of jar files that contain Hibernate mapping resources,
+ * like "WEB-INF/lib/example.hbm.jar".
+ * <p>Can be used to add to mappings from a Hibernate XML config file,
+ * or to specify all mappings locally.
+ * @see org.hibernate.cfg.Configuration#addJar(java.io.File)
+ */
+ public void setMappingJarLocations(Resource[] mappingJarLocations) {
+ this.mappingJarLocations = mappingJarLocations;
+ }
+
+ /**
+ * Set locations of directories that contain Hibernate mapping resources,
+ * like "WEB-INF/mappings".
+ * <p>Can be used to add to mappings from a Hibernate XML config file,
+ * or to specify all mappings locally.
+ * @see org.hibernate.cfg.Configuration#addDirectory(java.io.File)
+ */
+ public void setMappingDirectoryLocations(Resource[] mappingDirectoryLocations) {
+ this.mappingDirectoryLocations = mappingDirectoryLocations;
+ }
+
+ /**
+ * Set Hibernate properties, such as "hibernate.dialect".
+ * <p>Can be used to override values in a Hibernate XML config file,
+ * or to specify all necessary properties locally.
+ * <p>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 #setDataSource
+ */
+ public void setHibernateProperties(Properties hibernateProperties) {
+ this.hibernateProperties = hibernateProperties;
+ }
+
+ /**
+ * Return the Hibernate properties, if any. Mainly available for
+ * configuration through property paths that specify individual keys.
+ */
+ public Properties getHibernateProperties() {
+ if (this.hibernateProperties == null) {
+ this.hibernateProperties = new Properties();
+ }
+ return this.hibernateProperties;
+ }
+
+ /**
+ * Set the JTA TransactionManager to be used for Hibernate's
+ * TransactionManagerLookup. Allows for using a Spring-managed
+ * JTA TransactionManager for Hibernate's cache synchronization.
+ * <p>Note: If this is set, the Hibernate settings should not define a
+ * transaction manager lookup to avoid meaningless double configuration.
+ * @see LocalTransactionManagerLookup
+ */
+ public void setJtaTransactionManager(TransactionManager jtaTransactionManager) {
+ this.jtaTransactionManager = jtaTransactionManager;
+ }
- private final SessionFactoryBeanDelegate delegate = new SessionFactoryBeanDelegate(this);
+ /**
+ * Set the Hibernate RegionFactory to use for the SessionFactory.
+ * Allows for using a Spring-managed RegionFactory instance.
+ * <p>As of Hibernate 3.3, this is the preferred mechanism for configuring
+ * caches, superseding the {@link #setCacheProvider CacheProvider SPI}.
+ * For Hibernate 3.2 compatibility purposes, the accepted reference is of type
+ * Object: the actual type is <code>org.hibernate.cache.RegionFactory</code>.
+ * <p>Note: If this is set, the Hibernate settings should not define a
+ * cache provider to avoid meaningless double configuration.
+ * @see org.hibernate.cache.RegionFactory
+ */
+ public void setCacheRegionFactory(Object cacheRegionFactory) {
+ this.cacheRegionFactory = cacheRegionFactory;
+ }
+ /**
+ * Set the Hibernate CacheProvider to use for the SessionFactory.
+ * Allows for using a Spring-managed CacheProvider instance.
+ * <p>Note: If this is set, the Hibernate settings should not define a
+ * cache provider to avoid meaningless double configuration.
+ * @deprecated as of Spring 3.0, following Hibernate 3.3's deprecation
+ * of the CacheProvider SPI
+ * @see #setCacheRegionFactory
+ */
@Deprecated
- public void setCacheProvider(org.hibernate.cache.CacheProvider cacheProvider) {
- delegate.setCacheProvider(cacheProvider);
+ public void setCacheProvider(CacheProvider cacheProvider) {
+ this.cacheProvider = cacheProvider;
}
- @Override
- protected final void preBuildSessionFactory() {
- delegate.preBuildSessionFactory();
+ /**
+ * Set the LobHandler to be used by the SessionFactory.
+ * Will be exposed at config time for UserType implementations.
+ * @see #getConfigTimeLobHandler
+ * @see org.hibernate.usertype.UserType
+ * @see org.springframework.orm.hibernate3.support.ClobStringType
+ * @see org.springframework.orm.hibernate3.support.BlobByteArrayType
+ * @see org.springframework.orm.hibernate3.support.BlobSerializableType
+ */
+ public void setLobHandler(LobHandler lobHandler) {
+ this.lobHandler = lobHandler;
+ }
+
+ /**
+ * 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.
+ * <p>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 HibernateTemplate#setEntityInterceptor
+ * @see HibernateInterceptor#setEntityInterceptor
+ * @see HibernateTransactionManager#setEntityInterceptor
+ * @see org.hibernate.cfg.Configuration#setInterceptor
+ */
+ public void setEntityInterceptor(Interceptor entityInterceptor) {
+ this.entityInterceptor = entityInterceptor;
}
+ /**
+ * Set a Hibernate NamingStrategy for the SessionFactory, determining the
+ * physical column and table names given the info in the mapping document.
+ * @see org.hibernate.cfg.Configuration#setNamingStrategy
+ */
+ public void setNamingStrategy(NamingStrategy namingStrategy) {
+ this.namingStrategy = namingStrategy;
+ }
+
+ /**
+ * Specify the Hibernate type definitions to register with the SessionFactory,
+ * as Spring TypeDefinitionBean instances. This is an alternative to specifying
+ * <&lt;typedef&gt; elements in Hibernate mapping files.
+ * <p>Unfortunately, Hibernate itself does not define a complete object that
+ * represents a type definition, hence the need for Spring's TypeDefinitionBean.
+ * @see TypeDefinitionBean
+ * @see org.hibernate.cfg.Mappings#addTypeDef(String, String, java.util.Properties)
+ */
+ public void setTypeDefinitions(TypeDefinitionBean[] typeDefinitions) {
+ this.typeDefinitions = typeDefinitions;
+ }
+
+ /**
+ * Specify the Hibernate FilterDefinitions to register with the SessionFactory.
+ * This is an alternative to specifying <&lt;filter-def&gt; elements in
+ * Hibernate mapping files.
+ * <p>Typically, the passed-in FilterDefinition objects will have been defined
+ * as Spring FilterDefinitionFactoryBeans, probably as inner beans within the
+ * LocalSessionFactoryBean definition.
+ * @see FilterDefinitionFactoryBean
+ * @see org.hibernate.cfg.Configuration#addFilterDefinition
+ */
+ public void setFilterDefinitions(FilterDefinition[] filterDefinitions) {
+ this.filterDefinitions = filterDefinitions;
+ }
+
+ /**
+ * Specify the cache strategies for entities (persistent classes or named entities).
+ * This configuration setting corresponds to the &lt;class-cache&gt; entry
+ * in the "hibernate.cfg.xml" configuration format.
+ * <p>For example:
+ * <pre>
+ * &lt;property name="entityCacheStrategies"&gt;
+ * &lt;props&gt;
+ * &lt;prop key="com.mycompany.Customer"&gt;read-write&lt;/prop&gt;
+ * &lt;prop key="com.mycompany.Product"&gt;read-only,myRegion&lt;/prop&gt;
+ * &lt;/props&gt;
+ * &lt;/property&gt;</pre>
+ * @param entityCacheStrategies properties that define entity cache strategies,
+ * with class names as keys and cache concurrency strategies as values
+ * @see org.hibernate.cfg.Configuration#setCacheConcurrencyStrategy(String, String)
+ */
+ public void setEntityCacheStrategies(Properties entityCacheStrategies) {
+ this.entityCacheStrategies = entityCacheStrategies;
+ }
+
+ /**
+ * Specify the cache strategies for persistent collections (with specific roles).
+ * This configuration setting corresponds to the &lt;collection-cache&gt; entry
+ * in the "hibernate.cfg.xml" configuration format.
+ * <p>For example:
+ * <pre>
+ * &lt;property name="collectionCacheStrategies"&gt;
+ * &lt;props&gt;
+ * &lt;prop key="com.mycompany.Order.items">read-write&lt;/prop&gt;
+ * &lt;prop key="com.mycompany.Product.categories"&gt;read-only,myRegion&lt;/prop&gt;
+ * &lt;/props&gt;
+ * &lt;/property&gt;</pre>
+ * @param collectionCacheStrategies properties that define collection cache strategies,
+ * with collection roles as keys and cache concurrency strategies as values
+ * @see org.hibernate.cfg.Configuration#setCollectionCacheConcurrencyStrategy(String, String)
+ */
+ public void setCollectionCacheStrategies(Properties collectionCacheStrategies) {
+ this.collectionCacheStrategies = collectionCacheStrategies;
+ }
+
+ /**
+ * 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.
+ * <p>See the Hibernate documentation for further details on listener types
+ * and associated listener interfaces.
+ * @param eventListeners Map with listener type Strings as keys and
+ * listener objects as values
+ * @see org.hibernate.cfg.Configuration#setListener(String, Object)
+ */
+ public void setEventListeners(Map<String, Object> eventListeners) {
+ this.eventListeners = eventListeners;
+ }
+
+ /**
+ * Set whether to execute a schema update after SessionFactory initialization.
+ * <p>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 org.hibernate.cfg.Configuration#generateSchemaUpdateScript
+ * @see org.hibernate.tool.hbm2ddl.SchemaUpdate
+ */
+ public void setSchemaUpdate(boolean schemaUpdate) {
+ this.schemaUpdate = schemaUpdate;
+ }
+
+ public void setBeanClassLoader(ClassLoader beanClassLoader) {
+ this.beanClassLoader = beanClassLoader;
+ }
+
+
@Override
- protected final void postBuildSessionFactory() {
- delegate.postBuildSessionFactory();
+ @SuppressWarnings("unchecked")
+ protected SessionFactory buildSessionFactory() throws Exception {
+ // Create Configuration instance.
+ Configuration config = newConfiguration();
+
+ DataSource dataSource = getDataSource();
+ if (dataSource != null) {
+ // Make given DataSource available for SessionFactory configuration.
+ configTimeDataSourceHolder.set(dataSource);
+ }
+ if (this.jtaTransactionManager != null) {
+ // Make Spring-provided JTA TransactionManager available.
+ configTimeTransactionManagerHolder.set(this.jtaTransactionManager);
+ }
+ if (this.cacheRegionFactory != null) {
+ // Make Spring-provided Hibernate RegionFactory available.
+ configTimeRegionFactoryHolder.set(this.cacheRegionFactory);
+ }
+ if (this.cacheProvider != null) {
+ // Make Spring-provided Hibernate CacheProvider available.
+ configTimeCacheProviderHolder.set(this.cacheProvider);
+ }
+ if (this.lobHandler != null) {
+ // Make given LobHandler available for SessionFactory configuration.
+ // Do early because because mapping resource might refer to custom types.
+ configTimeLobHandlerHolder.set(this.lobHandler);
+ }
+
+ // Analogous to Hibernate EntityManager's Ejb3Configuration:
+ // Hibernate doesn't allow setting the bean ClassLoader explicitly,
+ // so we need to expose it as thread context ClassLoader accordingly.
+ Thread currentThread = Thread.currentThread();
+ ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
+ boolean overrideClassLoader =
+ (this.beanClassLoader != null && !this.beanClassLoader.equals(threadContextClassLoader));
+ if (overrideClassLoader) {
+ currentThread.setContextClassLoader(this.beanClassLoader);
+ }
+
+ try {
+ if (isExposeTransactionAwareSessionFactory()) {
+ // Set Hibernate 3.1+ CurrentSessionContext implementation,
+ // providing the Spring-managed Session as current Session.
+ // Can be overridden by a custom value for the corresponding Hibernate property.
+ config.setProperty(
+ Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
+ }
+
+ if (this.jtaTransactionManager != null) {
+ // Set Spring-provided JTA TransactionManager as Hibernate property.
+ config.setProperty(
+ Environment.TRANSACTION_STRATEGY, JTATransactionFactory.class.getName());
+ config.setProperty(
+ Environment.TRANSACTION_MANAGER_STRATEGY, LocalTransactionManagerLookup.class.getName());
+ }
+ else {
+ // Makes the Hibernate Session aware of the presence of a Spring-managed transaction.
+ // Also sets connection release mode to ON_CLOSE by default.
+ config.setProperty(
+ Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName());
+ }
+
+ if (this.entityInterceptor != null) {
+ // Set given entity interceptor at SessionFactory level.
+ config.setInterceptor(this.entityInterceptor);
+ }
+
+ if (this.namingStrategy != null) {
+ // Pass given naming strategy to Hibernate Configuration.
+ config.setNamingStrategy(this.namingStrategy);
+ }
+
+ if (this.typeDefinitions != null) {
+ // Register specified Hibernate type definitions.
+ // Use reflection for compatibility with both Hibernate 3.3 and 3.5:
+ // the returned Mappings object changed from a class to an interface.
+ Method createMappings = Configuration.class.getMethod("createMappings");
+ Method addTypeDef = createMappings.getReturnType().getMethod(
+ "addTypeDef", String.class, String.class, Properties.class);
+ Object mappings = ReflectionUtils.invokeMethod(createMappings, config);
+ for (TypeDefinitionBean typeDef : this.typeDefinitions) {
+ ReflectionUtils.invokeMethod(addTypeDef, mappings,
+ typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
+ }
+ }
+
+ if (this.filterDefinitions != null) {
+ // Register specified Hibernate FilterDefinitions.
+ for (FilterDefinition filterDef : this.filterDefinitions) {
+ config.addFilterDefinition(filterDef);
+ }
+ }
+
+ if (this.configLocations != null) {
+ for (Resource resource : this.configLocations) {
+ // Load Hibernate configuration from given location.
+ config.configure(resource.getURL());
+ }
+ }
+
+ if (this.hibernateProperties != null) {
+ // Add given Hibernate properties to Configuration.
+ config.addProperties(this.hibernateProperties);
+ }
+
+ if (dataSource != null) {
+ Class providerClass = LocalDataSourceConnectionProvider.class;
+ if (isUseTransactionAwareDataSource() || dataSource instanceof TransactionAwareDataSourceProxy) {
+ providerClass = TransactionAwareDataSourceConnectionProvider.class;
+ }
+ else if (config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY) != null) {
+ providerClass = LocalJtaDataSourceConnectionProvider.class;
+ }
+ // Set Spring-provided DataSource as Hibernate ConnectionProvider.
+ config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
+ }
+
+ if (this.cacheRegionFactory != null) {
+ // Expose Spring-provided Hibernate RegionFactory.
+ config.setProperty(Environment.CACHE_REGION_FACTORY,
+ "org.springframework.orm.hibernate3.LocalRegionFactoryProxy");
+ }
+ else if (this.cacheProvider != null) {
+ // Expose Spring-provided Hibernate CacheProvider.
+ config.setProperty(Environment.CACHE_PROVIDER, LocalCacheProviderProxy.class.getName());
+ }
+
+ if (this.mappingResources != null) {
+ // Register given Hibernate mapping definitions, contained in resource files.
+ for (String mapping : this.mappingResources) {
+ Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
+ config.addInputStream(resource.getInputStream());
+ }
+ }
+
+ if (this.mappingLocations != null) {
+ // Register given Hibernate mapping definitions, contained in resource files.
+ for (Resource resource : this.mappingLocations) {
+ config.addInputStream(resource.getInputStream());
+ }
+ }
+
+ if (this.cacheableMappingLocations != null) {
+ // Register given cacheable Hibernate mapping definitions, read from the file system.
+ for (Resource resource : this.cacheableMappingLocations) {
+ config.addCacheableFile(resource.getFile());
+ }
+ }
+
+ if (this.mappingJarLocations != null) {
+ // Register given Hibernate mapping definitions, contained in jar files.
+ for (Resource resource : this.mappingJarLocations) {
+ config.addJar(resource.getFile());
+ }
+ }
+
+ if (this.mappingDirectoryLocations != null) {
+ // Register all Hibernate mapping definitions in the given directories.
+ for (Resource resource : this.mappingDirectoryLocations) {
+ File file = resource.getFile();
+ if (!file.isDirectory()) {
+ throw new IllegalArgumentException(
+ "Mapping directory location [" + resource + "] does not denote a directory");
+ }
+ config.addDirectory(file);
+ }
+ }
+
+ // Tell Hibernate to eagerly compile the mappings that we registered,
+ // for availability of the mapping information in further processing.
+ postProcessMappings(config);
+ config.buildMappings();
+
+ if (this.entityCacheStrategies != null) {
+ // Register cache strategies for mapped entities.
+ for (Enumeration classNames = this.entityCacheStrategies.propertyNames(); classNames.hasMoreElements();) {
+ String className = (String) classNames.nextElement();
+ String[] strategyAndRegion =
+ StringUtils.commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
+ if (strategyAndRegion.length > 1) {
+ // method signature declares return type as Configuration on Hibernate 3.6
+ // but as void on Hibernate 3.3 and 3.5
+ Method setCacheConcurrencyStrategy = Configuration.class.getMethod(
+ "setCacheConcurrencyStrategy", String.class, String.class, String.class);
+ ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, config,
+ className, strategyAndRegion[0], strategyAndRegion[1]);
+ }
+ else if (strategyAndRegion.length > 0) {
+ 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 (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) {
+ String listenerType = entry.getKey();
+ Object listenerObject = entry.getValue();
+ if (listenerObject instanceof Collection) {
+ Collection<Object> listeners = (Collection<Object>) 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) {
+ configTimeDataSourceHolder.remove();
+ }
+ if (this.jtaTransactionManager != null) {
+ configTimeTransactionManagerHolder.remove();
+ }
+ if (this.cacheRegionFactory != null) {
+ configTimeCacheProviderHolder.remove();
+ }
+ if (this.cacheProvider != null) {
+ configTimeCacheProviderHolder.remove();
+ }
+ if (this.lobHandler != null) {
+ configTimeLobHandlerHolder.remove();
+ }
+ if (overrideClassLoader) {
+ // Reset original thread context ClassLoader.
+ currentThread.setContextClassLoader(threadContextClassLoader);
+ }
+ }
}
- public void destroy() throws HibernateException {
- delegate.destroy();
+ /**
+ * 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 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 {
}
- public SessionFactory getObject() throws Exception {
- return delegate.getSessionFactory();
+ /**
+ * 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 {
}
- public Class<? extends SessionFactory> getObjectType() {
- return delegate.getObjectType();
+ /**
+ * 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();
}
- public void setBeanClassLoader(ClassLoader classLoader) {
- delegate.setBeanClassLoader(classLoader);
+ /**
+ * 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;
}
- public boolean isSingleton() {
- return delegate.isSingleton();
+ /**
+ * Executes schema update if requested.
+ * @see #setSchemaUpdate
+ * @see #updateDatabaseSchema()
+ */
+ @Override
+ protected void afterSessionFactoryCreation() throws Exception {
+ if (this.schemaUpdate) {
+ updateDatabaseSchema();
+ }
}
- public void afterPropertiesSet() throws Exception {
- delegate.afterPropertiesSet();
+ /**
+ * Allows for schema export on shutdown.
+ */
+ @Override
+ 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.remove();
+ }
+ }
}
- public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
- return delegate.translateExceptionIfPossible(ex);
+
+ /**
+ * 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 {