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 9e8259198f.

Issue: SPR-8066, SPR-7936, SPR-8076, SPR-8098, SPR-8096, SPR-7387
This commit is contained in:
Chris Beams 2011-10-09 07:55:52 +00:00
parent 25796448f6
commit 3bb01ee68b
38 changed files with 1772 additions and 3039 deletions

View File

@ -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 File

@ -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 File

@ -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 File

@ -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 File

@ -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 File

@ -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 File

@ -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 File

@ -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 File

@ -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 @@ import org.springframework.util.ReflectionUtils;
* 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 @@ public class FilterDefinitionFactoryBean implements FactoryBean<FilterDefinition
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 File

@ -181,13 +181,12 @@ public abstract class HibernateAccessor implements InitializingBean, BeanFactory
* 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 abstract class HibernateAccessor implements InitializingBean, BeanFactory
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 abstract class HibernateAccessor implements InitializingBean, BeanFactory
* 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 abstract class HibernateAccessor implements InitializingBean, BeanFactory
* 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 File

@ -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 File

@ -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.DetachedCriteria;
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 @@ import org.springframework.util.Assert;
* 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 @@ import org.springframework.util.Assert;
* @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 File

@ -80,9 +80,8 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
* 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 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
* @since 1.2
* @see #setSessionFactory
* @see #setDataSource
* @see SessionFactoryBuilder
* @see LocalSessionFactoryBean
* @see SessionFactoryUtils#getSession
* @see SessionFactoryUtils#applyTransactionTimeout
@ -131,7 +129,6 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
* @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 class HibernateTransactionManager extends AbstractPlatformTransactionMana
* 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 class HibernateTransactionManager extends AbstractPlatformTransactionMana
* 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 class HibernateTransactionManager extends AbstractPlatformTransactionMana
/**
* 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 class HibernateTransactionManager extends AbstractPlatformTransactionMana
* 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 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
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 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
"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 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
// 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 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana
// 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 File

@ -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 @@ import org.hibernate.cache.CacheProvider;
* "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 File

@ -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 @@ package org.springframework.orm.hibernate3;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.HibernateException;
@ -29,12 +28,12 @@ import org.hibernate.util.JDBCExceptionReporter;
/**
* 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 class LocalDataSourceConnectionProvider implements ConnectionProvider {
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 class LocalDataSourceConnectionProvider implements ConnectionProvider {
* 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 File

@ -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 @@ package org.springframework.orm.hibernate3;
/**
* 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 File

@ -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 @@ import org.springframework.util.ReflectionUtils;
/**
* 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 @@ import org.springframework.util.ReflectionUtils;
*
* @author Juergen Hoeller
* @since 3.0
* @see SessionFactoryBuilder#setCacheRegionFactory
* @see LocalSessionFactoryBean#setCacheRegionFactory
*/
public class LocalRegionFactoryProxy implements RegionFactory {
@ -52,11 +52,11 @@ public class LocalRegionFactoryProxy implements RegionFactory {
* 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 File

@ -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.
@ -26,11 +26,11 @@ import org.hibernate.transaction.TransactionManagerLookup;
/**
* Implementation of Hibernate's {@link TransactionManagerLookup} interface
* that returns a Spring-managed JTA {@link TransactionManager}, determined
* by SessionFactoryBuilder's "jtaTransactionManager" property.
* by LocalSessionFactoryBean's "jtaTransactionManager" property.
*
* <p>The main advantage of this TransactionManagerLookup is that it avoids
* double configuration of JTA specifics. A single TransactionManager bean can
* be used for both JtaTransactionManager and SessionFactoryBuilder, with no
* be used for both JtaTransactionManager and LocalSessionFactoryBean, with no
* JTA setup in Hibernate configuration.
*
* <p>Alternatively, use Hibernate's own TransactionManagerLookup implementations:
@ -40,7 +40,7 @@ import org.hibernate.transaction.TransactionManagerLookup;
*
* @author Juergen Hoeller
* @since 1.2
* @see SessionFactoryBuilder#setJtaTransactionManager
* @see LocalSessionFactoryBean#setJtaTransactionManager
* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager
*/
public class LocalTransactionManagerLookup implements TransactionManagerLookup {
@ -49,11 +49,11 @@ public class LocalTransactionManagerLookup implements TransactionManagerLookup {
public LocalTransactionManagerLookup() {
TransactionManager tm = SessionFactoryBuilderSupport.getConfigTimeTransactionManager();
TransactionManager tm = LocalSessionFactoryBean.getConfigTimeTransactionManager();
// absolutely needs thread-bound TransactionManager to initialize
if (tm == null) {
throw new IllegalStateException("No JTA TransactionManager found - " +
"'jtaTransactionManager' property must be set on SessionFactoryBuilder");
"'jtaTransactionManager' property must be set on LocalSessionFactoryBean");
}
this.transactionManager = tm;
}

View File

@ -1,198 +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 javax.sql.DataSource;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cache.RegionFactory;
import org.hibernate.cfg.Environment;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.support.SQLExceptionTranslator;
/**
* Encapsulates common {@link SessionFactoryBeanOperations} behavior in order
* to avoid multiple-inheritance issues with {@code SessionFactoryBeanOperations}
* implementations that need to extend {@code *SessionFactoryBuilder} types.
*
* <p>Maintainer's note: Unless otherwise documented, JavaDoc for all methods is
* inherited from {@link SessionFactoryBeanOperations}.
*
* @author Chris Beams
* @since 3.1
*/
public class SessionFactoryBeanDelegate implements SessionFactoryBeanOperations {
private SessionFactory sessionFactory;
private HibernateExceptionTranslator hibernateExceptionTranslator = new HibernateExceptionTranslator();
private final SessionFactoryBuilderSupport<?> builder;
private final ThreadContextClassLoaderHelper threadContextClassLoader = new ThreadContextClassLoaderHelper();
@Deprecated
private org.hibernate.cache.CacheProvider cacheProvider;
@Deprecated
private static final ThreadLocal<org.hibernate.cache.CacheProvider> configTimeCacheProviderHolder =
new ThreadLocal<org.hibernate.cache.CacheProvider>();
/**
* Create a new {@code SessionFactoryBeanDelegate}
* @param builder the {@code *SessionFactoryBuilder} that delegates to this
* instance.
*/
public SessionFactoryBeanDelegate(SessionFactoryBuilderSupport<?> builder) {
this.builder = builder;
}
/**
* Return the {@code SessionFactory} maintained by this delegate.
*/
public SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* 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
* @deprecated as of Spring 3.1 in favor of Hibernate's {@link RegionFactory} SPI
*/
@Deprecated
public static org.hibernate.cache.CacheProvider getConfigTimeCacheProvider() {
return configTimeCacheProviderHolder.get();
}
@Deprecated
public void setCacheProvider(org.hibernate.cache.CacheProvider cacheProvider) {
this.cacheProvider = cacheProvider;
}
public void setPersistenceExceptionTranslator(HibernateExceptionTranslator hibernateExceptionTranslator) {
this.hibernateExceptionTranslator = hibernateExceptionTranslator;
}
public void setBeanClassLoader(ClassLoader beanClassLoader) {
builder.setClassLoader(beanClassLoader);
}
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;
}
public void afterPropertiesSet() throws Exception {
SessionFactory rawSf = builder.doBuildSessionFactory();
this.sessionFactory = builder.wrapSessionFactoryIfNecessary(rawSf);
builder.afterSessionFactoryCreation();
}
public void destroy() throws HibernateException {
builder.logger.info("Closing Hibernate SessionFactory");
DataSource dataSource = builder.getDataSource();
if (dataSource != null) {
// Make given DataSource available for potential SchemaExport,
// which unfortunately reinstantiates a ConnectionProvider.
SessionFactoryBuilderSupport.configTimeDataSourceHolder.set(dataSource);
}
try {
builder.beforeSessionFactoryDestruction();
}
finally {
this.sessionFactory.close();
if (dataSource != null) {
// Reset DataSource holder.
SessionFactoryBuilderSupport.configTimeDataSourceHolder.remove();
}
}
}
public void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator) {
this.hibernateExceptionTranslator.setJdbcExceptionTranslator(jdbcExceptionTranslator);
}
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
return hibernateExceptionTranslator.translateExceptionIfPossible(ex);
}
/**
* @see SessionFactoryBuilderSupport#preBuildSessionFactory()
*/
@SuppressWarnings("deprecation")
public void preBuildSessionFactory() {
if (this.cacheProvider != null) {
// Make Spring-provided Hibernate CacheProvider available.
configTimeCacheProviderHolder.set(this.cacheProvider);
}
if (builder.getCacheRegionFactory() == null && this.cacheProvider != null) {
// Expose Spring-provided Hibernate CacheProvider.
builder.getConfiguration().setProperty(Environment.CACHE_PROVIDER, LocalCacheProviderProxy.class.getName());
}
// 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.
threadContextClassLoader.overrideIfNecessary();
}
/**
* @see SessionFactoryBuilderSupport#postBuildSessionFactory
*/
public void postBuildSessionFactory() {
if (this.cacheProvider != null) {
configTimeCacheProviderHolder.remove();
}
threadContextClassLoader.resetIfNecessary();
}
private class ThreadContextClassLoaderHelper {
private Thread currentThread = Thread.currentThread();
private boolean shouldOverride = false;
private ClassLoader originalLoader;
void overrideIfNecessary() {
this.originalLoader = currentThread.getContextClassLoader();
this.shouldOverride =
(builder.getBeanClassLoader() != null && !builder.getBeanClassLoader().equals(this.originalLoader));
if (shouldOverride) {
this.currentThread.setContextClassLoader(builder.getBeanClassLoader());
}
}
void resetIfNecessary() {
if (this.shouldOverride) {
// Reset original thread context ClassLoader.
this.currentThread.setContextClassLoader(this.originalLoader);
}
}
}
}

View File

@ -1,128 +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.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cache.RegionFactory;
import org.springframework.beans.factory.BeanClassLoaderAware;
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;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
/**
* Operations common to {@link LocalSessionFactoryBean} and
* {@link AnnotationSessionFactoryBean} types but not available via
* their respective {@code *Builder} supertypes.
*
* @author Chris Beams
* @since 3.1
* @see LocalSessionFactoryBean
* @see AnnotationSessionFactoryBean
* @see SessionFactoryBeanDelegate
*/
public interface SessionFactoryBeanOperations
extends BeanClassLoaderAware, FactoryBean<SessionFactory>,
InitializingBean, DisposableBean, PersistenceExceptionTranslator {
/**
* <b>Deprecated.</b> <i>as of Spring 3.0 in favor of {@code setCacheRegionFactory}
* following Hibernate 3.3's deprecation of the {@code CacheProvider} SPI.</i>
* <p>Set the Hibernate {@code CacheProvider} to use for the {@code SessionFactory}.
* Allows for using a Spring-managed {@code CacheProvider} instance.
* <p>Note: If this is set, the Hibernate settings should not define a
* cache provider to avoid meaningless double configuration.
* of the {@code CacheProvider} SPI in favor of {@link RegionFactory} SPI.
*/
@Deprecated
void setCacheProvider(org.hibernate.cache.CacheProvider cacheProvider);
/**
* Customize the {@code HibernateExceptionTranslator} to be used when translating native
* {@code HibernateException} types to Spring's {@code DataAccessException} hierarchy.
*/
void setPersistenceExceptionTranslator(HibernateExceptionTranslator hibernateExceptionTranslator);
/**
* Exists for compatibility with {@link BeanClassLoaderAware} but
* simply delegates to
* {@link SessionFactoryBuilderSupport#setClassLoader setClassLoader}.
*/
void setBeanClassLoader(ClassLoader beanClassLoader);
/**
* Return the singleton SessionFactory.
*/
SessionFactory getObject() throws Exception;
/**
* Return the SessionFactory class used.
*/
Class<? extends SessionFactory> getObjectType();
/**
* Return {@code true}.
*/
boolean isSingleton();
/**
* Build and expose the SessionFactory.
* @see SessionFactoryBuilderSupport#buildSessionFactory
* @see SessionFactoryBuilderSupport#doBuildSessionFactory
* @see SessionFactoryBuilderSupport#wrapSessionFactoryIfNecessary
* @see SessionFactoryBuilderSupport#afterSessionFactoryCreation
*/
void afterPropertiesSet() throws Exception;
/**
* Close the SessionFactory on bean factory shutdown.
*/
void destroy() throws HibernateException;
/**
* Set the JDBC exception translator for the SessionFactory
* on this instance's underlying {@link #setPersistenceExceptionTranslator
* HibernateExceptionTranslator}.
* <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 #setPersistenceExceptionTranslator(HibernateExceptionTranslator)
* @see HibernateExceptionTranslator#setJdbcExceptionTranslator
* @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
*/
void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator);
/**
* 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
*/
DataAccessException translateExceptionIfPossible(RuntimeException ex);
}

View File

@ -1,101 +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 javax.sql.DataSource;
import org.hibernate.cfg.Configuration;
import org.springframework.context.annotation.Bean;
/**
* Hibernate {@link Configuration} builder suitable for use within Spring
* {@link org.springframework.context.annotation.Configuration @Configuration}
* class {@link Bean @Bean} methods. For complete details on features, see the
* JavaDoc for the {@link SessionFactoryBuilderSupport} superclass. For use in
* Spring XML configuration, see the {@link LocalSessionFactoryBean} subclass.
*
* <p>As noted in {@code SessionFactoryBuilderSupport} JavaDoc, this class requires
* Hibernate 3.2 or later; it additionally requires that the Java Persistence API
* and Hibernate Annotations add-ons are present.
*
* <p>Setter methods return the builder instance in order to facilitate
* a concise and convenient method-chaining style. For example:
* <pre class="code">
* {@code @Configuration}
* public class DataConfig {
* {@code @Bean}
* public SessionFactory sessionFactory() {
* return new SessionFactoryBean()
* .setDataSource(dataSource())
* .setMappingLocations("classpath:com/myco/*.hbm.xml"})
* .buildSessionFactory();
* }
* }
* </pre>
*
* <p>Most Hibernate configuration operations can be performed directly against
* this API; however you may also access access and configure the underlying
* {@code Configuration} object by using the {@link #doWithConfiguration} method
* and providing a {@code HibernateConfigurationCallback} as follows:
* <pre class="code">
* SessionFactory sessionFactory =
* new SessionFactoryBuilder()
* // ...
* .doWithConfiguration(new HibernateConfigurationCallback&lt;Configuration&gt;() {
* public void configure(Configuration cfg) {
* cfg.setNamingStrategy(MyNamingStrategy.class);
* }
* })
* .buildSessionFactory();
* </pre>
*
* @author Juergen Hoeller
* @author Chris Beams
* @since 3.1
* @see SessionFactoryBuilderSupport
* @see LocalSessionFactoryBean
* @see org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBuilder
* @see org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
*/
public class SessionFactoryBuilder extends SessionFactoryBuilderSupport<SessionFactoryBuilder> {
/**
* Construct a new {@code SessionFactoryBuilder}
*/
public SessionFactoryBuilder() {
super();
}
/**
* Construct a new {@code SessionFactoryBuilder} with the given
* Spring-managed {@code DataSource} instance.
* @see #setDataSource
*/
public SessionFactoryBuilder(DataSource dataSource) {
super(dataSource);
}
/**
* {@inheritDoc}
* <p>This implementation returns {@code org.hibernate.cfg.Configuration}
*/
@Override
protected Class<? extends Configuration> getDefaultConfigurationClass() {
return Configuration.class;
}
}

View File

@ -212,7 +212,7 @@ public abstract class SessionFactoryUtils {
* <p>Supports setting a Session-level Hibernate entity interceptor that allows
* to inspect and change property values before writing to and reading from the
* database. Such an interceptor can also be set at the SessionFactory level
* (i.e. on SessionFactoryBuilder), on HibernateTransactionManager, or on
* (i.e. on LocalSessionFactoryBean), on HibernateTransactionManager, or on
* HibernateInterceptor/HibernateTemplate.
* @param sessionFactory Hibernate SessionFactory to create the session with
* @param entityInterceptor Hibernate entity interceptor, or <code>null</code> if none
@ -221,7 +221,7 @@ public abstract class SessionFactoryUtils {
* when actually registering a transaction synchronization)
* @return the Hibernate Session
* @throws DataAccessResourceFailureException if the Session couldn't be created
* @see SessionFactoryBuilder#setEntityInterceptor
* @see LocalSessionFactoryBean#setEntityInterceptor
* @see HibernateInterceptor#setEntityInterceptor
* @see HibernateTemplate#setEntityInterceptor
*/

View File

@ -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.
@ -26,7 +26,7 @@ import org.hibernate.engine.SessionFactoryImplementor;
* that delegates to Spring's SessionFactoryUtils for providing a
* Spring-managed current Session.
*
* <p>Used by Spring's {@link SessionFactoryBuilder} when told to expose a
* <p>Used by Spring's {@link LocalSessionFactoryBean} when told to expose a
* transaction-aware SessionFactory. This is the default as of Spring 2.5.
*
* <p>This CurrentSessionContext implementation can also be specified in custom
@ -36,9 +36,8 @@ import org.hibernate.engine.SessionFactoryImplementor;
* @author Juergen Hoeller
* @since 2.0
* @see SessionFactoryUtils#doGetSession
* @see SessionFactoryBuilder#setExposeTransactionAwareSessionFactory
* @see LocalSessionFactoryBean#setExposeTransactionAwareSessionFactory
*/
@SuppressWarnings("serial")
public class SpringSessionContext implements CurrentSessionContext {
private final SessionFactoryImplementor sessionFactory;

View File

@ -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.
@ -23,11 +23,11 @@ import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
/**
* Subclass of LocalDataSourceConnectionProvider that returns a
* transaction-aware proxy for the exposed DataSource. Used if
* SessionFactoryBuilder's "useTransactionAwareDataSource" flag is on.
* LocalSessionFactoryBean's "useTransactionAwareDataSource" flag is on.
*
* @author Juergen Hoeller
* @since 1.2
* @see SessionFactoryBuilder#setUseTransactionAwareDataSource
* @see LocalSessionFactoryBean#setUseTransactionAwareDataSource
*/
public class TransactionAwareDataSourceConnectionProvider extends LocalDataSourceConnectionProvider {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2011 the original author or authors.
* Copyright 2002-2005 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,20 +28,19 @@ import org.springframework.beans.factory.InitializingBean;
* definition, as list element for the "typeDefinitions" 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="typeDefinitions">
* <list>
* <bean class="org.springframework.orm.hibernate3.TypeDefinitionBean">
* <property name="typeName" value="myType"/>
* <property name="typeClass" value="mypackage.MyTypeClass"/>
* </bean>
* </list>
* </property>
* &lt;property name="typeDefinitions"&gt;
* &lt;list&gt;
* &lt;bean class="org.springframework.orm.hibernate3.TypeDefinitionBean"&gt;
* &lt;property name="typeName" value="myType"/&gt;
* &lt;property name="typeClass" value="mypackage.MyTypeClass"/&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 "typeName" property.

View File

@ -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,169 +16,233 @@
package org.springframework.orm.hibernate3.annotation;
import java.io.IOException;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.MappingException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.springframework.orm.hibernate3.HibernateExceptionTranslator;
import org.springframework.orm.hibernate3.SessionFactoryBeanOperations;
import org.springframework.orm.hibernate3.SessionFactoryBeanDelegate;
import org.springframework.orm.hibernate3.SessionFactoryBuilderSupport;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
import org.springframework.util.ClassUtils;
/**
* Subclass of {@link AnnotationSessionFactoryBuilder} adhering to Spring's
* {@link org.springframework.beans.factory.FactoryBean FactoryBean} contract,
* making it suitable for use in XML configuration.
* Subclass of Spring's standard LocalSessionFactoryBean for Hibernate,
* supporting JDK 1.5+ annotation metadata for mappings.
*
* <p>A typical {@code AnnotationSessionFactoryBean} bean definition:
* <p>Note: This class requires Hibernate 3.2 or later, with the
* Java Persistence API and the Hibernate Annotations add-on present.
*
* <p>Example for an AnnotationSessionFactoryBean bean definition:
*
* <pre class="code">
* {@code
* <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
* <property name="dataSource" ref="dataSource"/>
* <property name="annotatedClasses">
* <list>
* <value>test.package.Foo</value>
* <value>test.package.Bar</value>
* </list>
* </property>
* </bean>}</pre>
* &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;
* &lt;property name="dataSource" ref="dataSource"/&gt;
* &lt;property name="annotatedClasses"&gt;
* &lt;list&gt;
* &lt;value&gt;test.package.Foo&lt;/value&gt;
* &lt;value&gt;test.package.Bar&lt;/value&gt;
* &lt;/list&gt;
* &lt;/property&gt;
* &lt;/bean&gt;</pre>
*
* Or when using classpath scanning for autodetection of entity classes:
*
* <pre class="code">
* {@code
* <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
* <property name="dataSource" ref="dataSource"/>
* <property name="packagesToScan" value="test.package"/>
* </bean>}</pre>
*
* <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 AnnotationSessionFactoryBean} automatically
* enables a {@code PersistenceExceptionTranslationPostProcessor} to translate
* Hibernate exceptions.
* &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;
* &lt;property name="dataSource" ref="dataSource"/&gt;
* &lt;property name="packagesToScan" value="test.package"/&gt;
* &lt;/bean&gt;</pre>
*
* @author Juergen Hoeller
* @author Chris Beams
* @since 1.2.2
* @see SessionFactoryBuilderSupport
* @see AnnotationSessionFactoryBuilder
* @see #setDataSource
* @see #setHibernateProperties
* @see #setAnnotatedClasses
* @see #setAnnotatedPackages
*/
public class AnnotationSessionFactoryBean extends AnnotationSessionFactoryBuilder
implements SessionFactoryBeanOperations, ResourceLoaderAware {
public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implements ResourceLoaderAware {
private final SessionFactoryBeanDelegate delegate = new SessionFactoryBeanDelegate(this);
private static final String RESOURCE_PATTERN = "/**/*.class";
@Deprecated
public void setCacheProvider(org.hibernate.cache.CacheProvider cacheProvider) {
delegate.setCacheProvider(cacheProvider);
private Class[] annotatedClasses;
private String[] annotatedPackages;
private String[] packagesToScan;
private TypeFilter[] entityTypeFilters = new TypeFilter[] {
new AnnotationTypeFilter(Entity.class, false),
new AnnotationTypeFilter(Embeddable.class, false),
new AnnotationTypeFilter(MappedSuperclass.class, false),
new AnnotationTypeFilter(org.hibernate.annotations.Entity.class, false)};
private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
public AnnotationSessionFactoryBean() {
setConfigurationClass(AnnotationConfiguration.class);
}
@Override
protected void preBuildSessionFactory() {
delegate.preBuildSessionFactory();
}
@Override
protected void postBuildSessionFactory() {
delegate.postBuildSessionFactory();
public void setConfigurationClass(Class configurationClass) {
if (configurationClass == null || !AnnotationConfiguration.class.isAssignableFrom(configurationClass)) {
throw new IllegalArgumentException(
"AnnotationSessionFactoryBean only supports AnnotationConfiguration or subclasses");
}
super.setConfigurationClass(configurationClass);
}
/**
* Specify annotated classes, for which mappings will be read from
* class-level JDK 1.5+ annotation metadata.
* @see org.hibernate.cfg.AnnotationConfiguration#addAnnotatedClass(Class)
*/
public void setAnnotatedClasses(Class[] annotatedClasses) {
this.annotatedClasses = annotatedClasses;
}
/**
* Specify the names of annotated packages, for which package-level
* JDK 1.5+ annotation metadata will be read.
* @see org.hibernate.cfg.AnnotationConfiguration#addPackage(String)
*/
public void setAnnotatedPackages(String[] annotatedPackages) {
this.annotatedPackages = annotatedPackages;
}
/**
* Set whether to use Spring-based scanning for entity classes in the classpath
* instead of listing annotated classes explicitly.
* <p>Default is none. Specify packages to search for autodetection of your entity
* classes in the classpath. This is analogous to Spring's component-scan feature
* ({@link org.springframework.context.annotation.ClassPathBeanDefinitionScanner}).
*/
public void setPackagesToScan(String[] packagesToScan) {
this.packagesToScan = packagesToScan;
}
/**
* Specify custom type filters for Spring-based scanning for entity classes.
* <p>Default is to search all specified packages for classes annotated with
* <code>@javax.persistence.Entity</code>, <code>@javax.persistence.Embeddable</code>
* or <code>@javax.persistence.MappedSuperclass</code>, as well as for
* Hibernate's special <code>@org.hibernate.annotations.Entity</code>.
* @see #setPackagesToScan
*/
public void setEntityTypeFilters(TypeFilter[] entityTypeFilters) {
this.entityTypeFilters = entityTypeFilters;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.setResourcePatternResolver(ResourcePatternUtils.getResourcePatternResolver(resourceLoader));
this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
public void destroy() throws HibernateException {
delegate.destroy();
}
public SessionFactory getObject() {
return delegate.getObject();
}
public Class<? extends SessionFactory> getObjectType() {
return delegate.getObjectType();
}
public void setBeanClassLoader(ClassLoader beanClassLoader) {
delegate.setBeanClassLoader(beanClassLoader);
}
public boolean isSingleton() {
return delegate.isSingleton();
}
public void afterPropertiesSet() throws Exception {
delegate.afterPropertiesSet();
}
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
return delegate.translateExceptionIfPossible(ex);
}
public void setJdbcExceptionTranslator(
SQLExceptionTranslator jdbcExceptionTranslator) {
delegate.setJdbcExceptionTranslator(jdbcExceptionTranslator);
}
public void setPersistenceExceptionTranslator(
HibernateExceptionTranslator hibernateExceptionTranslator) {
delegate.setPersistenceExceptionTranslator(hibernateExceptionTranslator);
/**
* Reads metadata from annotated classes and packages into the
* AnnotationConfiguration instance.
*/
@Override
protected void postProcessMappings(Configuration config) throws HibernateException {
AnnotationConfiguration annConfig = (AnnotationConfiguration) config;
if (this.annotatedClasses != null) {
for (Class annotatedClass : this.annotatedClasses) {
annConfig.addAnnotatedClass(annotatedClass);
}
}
if (this.annotatedPackages != null) {
for (String annotatedPackage : this.annotatedPackages) {
annConfig.addPackage(annotatedPackage);
}
}
scanPackages(annConfig);
}
/**
* @deprecated as of Spring 3.1 in favor of {@link #scanPackages()} which
* can access the internal {@code AnnotationConfiguration} instance via
* {@link #getConfiguration()}.
* Perform Spring-based scanning for entity classes.
* @see #setPackagesToScan
*/
@Deprecated
protected void scanPackages(org.hibernate.cfg.AnnotationConfiguration config) {
this.scanPackages();
protected void scanPackages(AnnotationConfiguration config) {
if (this.packagesToScan != null) {
try {
for (String pkg : this.packagesToScan) {
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
Resource[] resources = this.resourcePatternResolver.getResources(pattern);
MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader reader = readerFactory.getMetadataReader(resource);
String className = reader.getClassMetadata().getClassName();
if (matchesFilter(reader, readerFactory)) {
config.addAnnotatedClass(this.resourcePatternResolver.getClassLoader().loadClass(className));
}
}
}
}
}
catch (IOException ex) {
throw new MappingException("Failed to scan classpath for unlisted classes", ex);
}
catch (ClassNotFoundException ex) {
throw new MappingException("Failed to load annotated classes from classpath", ex);
}
}
}
/**
* @deprecated as of Spring 3.1 in favor of {@link #newSessionFactory()} which
* can access the internal {@code Configuration} instance via {@link #getConfiguration()}.
* Check whether any of the configured entity type filters matches
* the current class descriptor contained in the metadata reader.
*/
@Deprecated
protected SessionFactory newSessionFactory(org.hibernate.cfg.Configuration config) throws HibernateException {
return this.newSessionFactory();
private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException {
if (this.entityTypeFilters != null) {
for (TypeFilter filter : this.entityTypeFilters) {
if (filter.match(reader, readerFactory)) {
return true;
}
}
}
return false;
}
/**
* This default implementation delegates to {@link #postProcessAnnotationConfiguration}.
*/
@Override
protected void postProcessConfiguration(Configuration config) throws HibernateException {
postProcessAnnotationConfiguration((AnnotationConfiguration) config);
}
/**
* @deprecated as of Spring 3.1 in favor of {@link #postProcessMappings()} which
* can access the internal {@code Configuration} instance via {@link #getConfiguration()}.
* To be implemented by subclasses which want to to perform custom
* post-processing of the AnnotationConfiguration object after this
* FactoryBean performed its default initialization.
* <p>Note: As of Hibernate 3.6, AnnotationConfiguration's features
* have been rolled into Configuration itself. Simply overriding
* {@link #postProcessConfiguration(org.hibernate.cfg.Configuration)}
* becomes an option as well then.
* @param config the current AnnotationConfiguration object
* @throws HibernateException in case of Hibernate initialization errors
*/
@Deprecated
protected void postProcessMappings(org.hibernate.cfg.Configuration config) throws HibernateException {
this.postProcessMappings();
}
/**
* @deprecated as of Spring 3.1 in favor of {@link #postProcessConfiguration()} which
* can access the internal {@code Configuration} instance via {@link #getConfiguration()}.
*/
@Deprecated
protected void postProcessConfiguration(org.hibernate.cfg.Configuration config) throws HibernateException {
this.postProcessConfiguration();
}
/**
* @deprecated as of Spring 3.1 in favor of {@link #postProcessAnnotationConfiguration()}
* which can access the internal {@code AnnotationConfiguration} instance via
* {@link #getConfiguration()}.
*/
@Deprecated
protected void postProcessAnnotationConfiguration(org.hibernate.cfg.AnnotationConfiguration config) throws HibernateException {
this.postProcessAnnotationConfiguration();
protected void postProcessAnnotationConfiguration(AnnotationConfiguration config) throws HibernateException {
}
}

View File

@ -1,300 +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.annotation;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import javax.sql.DataSource;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.orm.hibernate3.SessionFactoryBuilderSupport;
import org.springframework.util.ClassUtils;
/**
* Hibernate {@link AnnotationConfiguration} builder suitable for use within Spring
* {@link org.springframework.context.annotation.Configuration @Configuration}
* class {@link Bean @Bean} methods. For complete details on features, see the
* JavaDoc for the {@link SessionFactoryBuilderSupport} superclass. For use in
* Spring XML configuration, see the {@link AnnotationSessionFactoryBean} subclass.
*
* <p>As noted in {@code SessionFactoryBuilderSupport} JavaDoc, this class requires
* Hibernate 3.2 or later; it additionally requires that the Java Persistence API
* and Hibernate Annotations add-ons are present.
*
* <p>Setter methods return the builder instance in order to facilitate
* a concise and convenient method-chaining style. For example:
* <pre class="code">
* {@code @Configuration}
* public class DataConfig {
* {@code @Bean}
* public SessionFactory sessionFactory() {
* return new AnnotationSessionFactoryBuilder()
* .setDataSource(dataSource())
* .setPackagesToScan("com.myco"})
* .buildSessionFactory();
* }
* }
* </pre>
*
* <p>Most Hibernate configuration operations can be performed directly against
* this API; however you may also access access and configure the underlying
* {@code AnnotationConfiguration} object by using the {@link #doWithConfiguration}
* method and providing a {@code HibernateConfigurationCallback} as follows:
* <pre class="code">
* SessionFactory sessionFactory =
* new AnnotationSessionFactoryBuilder()
* // ...
* .doWithConfiguration(new HibernateConfigurationCallback&lt;AnnotationConfiguration&gt;() {
* public void configure(AnnotationConfiguration cfg) {
* cfg.addAnnotatedClass(Foo.class);
* }
* })
* .buildSessionFactory();
* </pre>
*
* @author Juergen Hoeller
* @author Chris Beams
* @since 3.1
* @see org.springframework.orm.hibernate3.SessionFactoryBuilderSupport
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder
* @see AnnotationSessionFactoryBean
*/
public class AnnotationSessionFactoryBuilder extends SessionFactoryBuilderSupport<AnnotationSessionFactoryBuilder> {
/** Hibernate 3.6 consolidates Configuration and AnnotationConfiguration operations. */
private static final boolean hibernate36Present = ClassUtils.hasMethod(Configuration.class, "addAnnotatedClass", Class.class);
private static final String RESOURCE_PATTERN = "/**/*.class";
private Class<?>[] annotatedClasses;
private String[] annotatedPackages;
private String[] packagesToScan;
private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
private TypeFilter[] entityTypeFilters = new TypeFilter[] {
new AnnotationTypeFilter(Entity.class, false),
new AnnotationTypeFilter(Embeddable.class, false),
new AnnotationTypeFilter(MappedSuperclass.class, false),
new AnnotationTypeFilter(org.hibernate.annotations.Entity.class, false)};
/**
* Construct a new {@code AnnotationSessionFactoryBuilder}
*/
public AnnotationSessionFactoryBuilder() {
super();
}
/**
* Construct a new {@code AnnotationSessionFactoryBuilder} with the given
* Spring-managed {@code DataSource} instance.
* @see #setDataSource
*/
public AnnotationSessionFactoryBuilder(DataSource dataSource) {
super(dataSource);
}
/**
* {@inheritDoc}
* <p>This implementation returns {@link org.hibernate.cfg.Configuration} if
* Hibernate 3.6 or greater is available on the runtime classpath, otherwise
* {@link org.hibernate.cfg.AnnotationConfiguration}. This accommodates
* the consolidation of these two types and deprecation of the latter in
* Hibernate 3.6.
* @see #doWithConfiguration
*/
protected Class<? extends Configuration> getDefaultConfigurationClass() {
return hibernate36Present ? Configuration.class : AnnotationConfiguration.class;
}
/**
* Set whether to use Spring-based scanning for entity classes in the classpath
* instead of listing annotated classes explicitly.
* <p>Default is none. Specify packages to search for autodetection of your entity
* classes in the classpath. This is analogous to Spring's component-scan feature
* ({@link org.springframework.context.annotation.ClassPathBeanDefinitionScanner}).
*/
public AnnotationSessionFactoryBuilder setPackagesToScan(String... packagesToScan) {
this.packagesToScan = packagesToScan;
return this;
}
/**
* Specify annotated classes, for which mappings will be read from
* class-level JDK 1.5+ annotation metadata.
* @see org.hibernate.cfg.AnnotationConfiguration#addAnnotatedClass
*/
public AnnotationSessionFactoryBuilder setAnnotatedClasses(Class<?>... annotatedClasses) {
this.annotatedClasses = annotatedClasses;
return this;
}
/**
* Specify the names of annotated packages, for which package-level
* JDK 1.5+ annotation metadata will be read.
* @see org.hibernate.cfg.AnnotationConfiguration#addPackage
*/
public AnnotationSessionFactoryBuilder setAnnotatedPackages(String[] annotatedPackages) {
this.annotatedPackages = annotatedPackages;
return this;
}
/**
* Specify custom type filters for Spring-based scanning for entity classes.
* <p>Default is to search all specified packages for classes annotated with
* <code>@javax.persistence.Entity</code>, <code>@javax.persistence.Embeddable</code>
* or <code>@javax.persistence.MappedSuperclass</code>, as well as for
* Hibernate's special <code>@org.hibernate.annotations.Entity</code>.
* @see #setPackagesToScan
*/
public AnnotationSessionFactoryBuilder setEntityTypeFilters(TypeFilter[] entityTypeFilters) {
this.entityTypeFilters = entityTypeFilters;
return this;
}
public void setResourcePatternResolver(ResourcePatternResolver resourcePatternResolver) {
this.resourcePatternResolver = resourcePatternResolver;
}
/**
* Perform Spring-based scanning for entity classes.
* @see #setPackagesToScan
*/
protected void scanPackages() {
if (this.packagesToScan != null) {
try {
for (String pkg : this.packagesToScan) {
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
Resource[] resources = this.resourcePatternResolver.getResources(pattern);
MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader reader = readerFactory.getMetadataReader(resource);
String className = reader.getClassMetadata().getClassName();
if (matchesFilter(reader, readerFactory)) {
Class<?> annotatedClass = this.resourcePatternResolver.getClassLoader().loadClass(className);
invokeConfigurationMethod("addAnnotatedClass", Class.class, annotatedClass);
}
}
}
}
}
catch (IOException ex) {
throw new MappingException("Failed to scan classpath for unlisted classes", ex);
}
catch (ClassNotFoundException ex) {
throw new MappingException("Failed to load annotated classes from classpath", ex);
}
}
}
/**
* Check whether any of the configured entity type filters matches
* the current class descriptor contained in the metadata reader.
*/
private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException {
if (this.entityTypeFilters != null) {
for (TypeFilter filter : this.entityTypeFilters) {
if (filter.match(reader, readerFactory)) {
return true;
}
}
}
return false;
}
/**
* Reads metadata from annotated classes and packages into the
* AnnotationConfiguration instance.
*/
@Override
protected void postProcessMappings() throws HibernateException {
// org.hibernate.cfg.Configuration cfg = getConfiguration();
if (this.annotatedClasses != null) {
for (Class<?> annotatedClass : this.annotatedClasses) {
invokeConfigurationMethod("addAnnotatedClass", Class.class, annotatedClass);
}
}
if (this.annotatedPackages != null) {
for (String annotatedPackage : this.annotatedPackages) {
invokeConfigurationMethod("addPackage", String.class, annotatedPackage);
}
}
scanPackages();
}
/**
* Delegates to {@link #postProcessAnnotationConfiguration}.
*/
@Override
protected void postProcessConfiguration() throws HibernateException {
postProcessAnnotationConfiguration();
}
/**
* To be implemented by subclasses which want to to perform custom
* post-processing of the AnnotationConfiguration object after this
* FactoryBean performed its default initialization.
* <p>Note: As of Hibernate 3.6, AnnotationConfiguration's features
* have been rolled into Configuration itself. Simply overriding
* {@link #postProcessConfiguration(org.hibernate.cfg.Configuration)}
* becomes an option as well then.
* @param config the current AnnotationConfiguration object
* @throws HibernateException in case of Hibernate initialization errors
*/
protected void postProcessAnnotationConfiguration() throws HibernateException {
}
/**
* Reflectively invoke the given method against the underlying Configuration
* instance. In order to support the consolidation of Hibernate's
* AnnotationConfiguration into Configuration in Hibernate 3.6 while continuing
* to to compile against Hibernate 3.3.x, we must reflectively invoke in order
* to avoid compilation failure.
*/
private <T> void invokeConfigurationMethod(String methodName, Class<T> parameterType, T parameter) {
org.hibernate.cfg.Configuration cfg = getConfiguration();
try {
Method m = cfg.getClass().getMethod(methodName, parameterType);
m.invoke(cfg, parameter);
} catch (Exception ex) {
throw new IllegalStateException(String.format("Hibernate Configuration class [%s] does not support the '%s(%s)' method.",
cfg.getClass().getSimpleName(), methodName, parameterType.getSimpleName()));
}
}
}

View File

@ -22,6 +22,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.transaction.Status;
import javax.transaction.TransactionManager;
import org.apache.commons.logging.Log;
@ -29,18 +30,23 @@ import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import org.hibernate.util.EqualsHelper;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.jdbc.support.lob.JtaLobCreatorSynchronization;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobCreatorUtils;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.orm.hibernate3.SessionFactoryBuilderSupport;
import org.springframework.jdbc.support.lob.SpringLobCreatorSynchronization;
import org.springframework.jdbc.support.lob.LobCreatorUtils;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Abstract base class for Hibernate UserType implementations that map to LOBs.
* Retrieves the LobHandler to use from SessionFactoryBuilder at config time.
* Retrieves the LobHandler to use from LocalSessionFactoryBean at config time.
*
* <p>For writing LOBs, either an active Spring transaction synchronization
* or an active JTA transaction (with "jtaTransactionManager" specified on
* SessionFactoryBuilder or a Hibernate TransactionManagerLookup configured
* LocalSessionFactoryBean or a Hibernate TransactionManagerLookup configured
* through the corresponding Hibernate property) is required.
*
* <p>Offers template methods for setting parameters and getting result values,
@ -50,8 +56,8 @@ import org.springframework.orm.hibernate3.SessionFactoryBuilderSupport;
* @since 1.2
* @see org.springframework.jdbc.support.lob.LobHandler
* @see org.springframework.jdbc.support.lob.LobCreator
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#setLobHandler
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#setJtaTransactionManager
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setJtaTransactionManager
*/
public abstract class AbstractLobType implements UserType {
@ -64,13 +70,13 @@ public abstract class AbstractLobType implements UserType {
/**
* Constructor used by Hibernate: fetches config-time LobHandler and
* config-time JTA TransactionManager from the SessionFactory builder.
* @see org.springframework.orm.hibernate3.SessionFactoryBuilderSupport#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.SessionFactoryBuilderSupport#getConfigTimeTransactionManager
* config-time JTA TransactionManager from LocalSessionFactoryBean.
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeTransactionManager
*/
protected AbstractLobType() {
this(SessionFactoryBuilderSupport.getConfigTimeLobHandler(),
SessionFactoryBuilderSupport.getConfigTimeTransactionManager());
this(LocalSessionFactoryBean.getConfigTimeLobHandler(),
LocalSessionFactoryBean.getConfigTimeTransactionManager());
}
/**
@ -144,7 +150,7 @@ public abstract class AbstractLobType implements UserType {
if (this.lobHandler == null) {
throw new IllegalStateException("No LobHandler found for configuration - " +
"lobHandler property must be set on SessionFactoryBuilder");
"lobHandler property must be set on LocalSessionFactoryBean");
}
try {
@ -166,7 +172,7 @@ public abstract class AbstractLobType implements UserType {
if (this.lobHandler == null) {
throw new IllegalStateException("No LobHandler found for configuration - " +
"lobHandler property must be set on SessionFactoryBuilder");
"lobHandler property must be set on LocalSessionFactoryBean");
}
LobCreator lobCreator = this.lobHandler.getLobCreator();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2011 the original author or authors.
* Copyright 2002-2005 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.
@ -29,7 +29,7 @@ import org.springframework.jdbc.support.lob.LobHandler;
/**
* Hibernate UserType implementation for byte arrays that get mapped to BLOBs.
* Retrieves the LobHandler to use from SessionFactoryBuilder at config time.
* Retrieves the LobHandler to use from LocalSessionFactoryBean at config time.
*
* <p>Can also be defined in generic Hibernate mappings, as DefaultLobCreator will
* work with most JDBC-compliant database drivers. In this case, the field type
@ -38,15 +38,15 @@ import org.springframework.jdbc.support.lob.LobHandler;
*
* @author Juergen Hoeller
* @since 1.2
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#setLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setLobHandler
*/
public class BlobByteArrayType extends AbstractLobType {
/**
* Constructor used by Hibernate: fetches config-time LobHandler and
* config-time JTA TransactionManager from SessionFactoryBuilder.
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#getConfigTimeTransactionManager
* config-time JTA TransactionManager from LocalSessionFactoryBean.
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeTransactionManager
*/
public BlobByteArrayType() {
super();
@ -64,7 +64,7 @@ public class BlobByteArrayType extends AbstractLobType {
return new int[] {Types.BLOB};
}
public Class<?> returnedClass() {
public Class returnedClass() {
return byte[].class;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2011 the original author or authors.
* Copyright 2002-2005 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,7 +37,7 @@ import org.springframework.jdbc.support.lob.LobHandler;
/**
* Hibernate UserType implementation for arbitrary objects that get serialized to BLOBs.
* Retrieves the LobHandler to use from SessionFactoryBuilder at config time.
* Retrieves the LobHandler to use from LocalSessionFactoryBean at config time.
*
* <p>Can also be defined in generic Hibernate mappings, as DefaultLobCreator will
* work with most JDBC-compliant database drivers. In this case, the field type
@ -46,7 +46,7 @@ import org.springframework.jdbc.support.lob.LobHandler;
*
* @author Juergen Hoeller
* @since 1.2
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#setLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setLobHandler
*/
public class BlobSerializableType extends AbstractLobType {
@ -60,9 +60,9 @@ public class BlobSerializableType extends AbstractLobType {
/**
* Constructor used by Hibernate: fetches config-time LobHandler and
* config-time JTA TransactionManager from SessionFactoryBuilder.
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#getConfigTimeTransactionManager
* config-time JTA TransactionManager from LocalSessionFactoryBean.
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeTransactionManager
*/
public BlobSerializableType() {
super();
@ -80,7 +80,7 @@ public class BlobSerializableType extends AbstractLobType {
return new int[] {Types.BLOB};
}
public Class<?> returnedClass() {
public Class returnedClass() {
return Serializable.class;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2011 the original author or authors.
* Copyright 2002-2006 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.
@ -29,7 +29,7 @@ import org.springframework.jdbc.support.lob.LobHandler;
/**
* Hibernate UserType implementation for Strings that get mapped to BLOBs.
* Retrieves the LobHandler to use from SessionFactoryBuilder at config time.
* Retrieves the LobHandler to use from LocalSessionFactoryBean at config time.
*
* <p>This is intended for the (arguably unnatural, but still common) case
* where character data is stored in a binary LOB. This requires encoding
@ -44,15 +44,15 @@ import org.springframework.jdbc.support.lob.LobHandler;
* @author Juergen Hoeller
* @since 1.2.7
* @see #getCharacterEncoding()
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#setLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setLobHandler
*/
public class BlobStringType extends AbstractLobType {
/**
* Constructor used by Hibernate: fetches config-time LobHandler and
* config-time JTA TransactionManager from SessionFactoryBuilder.
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#getConfigTimeTransactionManager
* config-time JTA TransactionManager from LocalSessionFactoryBean.
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeTransactionManager
*/
public BlobStringType() {
super();
@ -70,7 +70,7 @@ public class BlobStringType extends AbstractLobType {
return new int[] {Types.BLOB};
}
public Class<?> returnedClass() {
public Class returnedClass() {
return String.class;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2011 the original author or authors.
* Copyright 2002-2005 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,7 +28,7 @@ import org.springframework.jdbc.support.lob.LobHandler;
/**
* Hibernate UserType implementation for Strings that get mapped to CLOBs.
* Retrieves the LobHandler to use from SessionFactoryBuilder at config time.
* Retrieves the LobHandler to use from LocalSessionFactoryBean at config time.
*
* <p>Particularly useful for storing Strings with more than 4000 characters in an
* Oracle database (only possible via CLOBs), in combination with OracleLobHandler.
@ -40,15 +40,15 @@ import org.springframework.jdbc.support.lob.LobHandler;
*
* @author Juergen Hoeller
* @since 1.2
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#setLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setLobHandler
*/
public class ClobStringType extends AbstractLobType {
/**
* Constructor used by Hibernate: fetches config-time LobHandler and
* config-time JTA TransactionManager from SessionFactoryBuilder.
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#getConfigTimeTransactionManager
* config-time JTA TransactionManager from LocalSessionFactoryBean.
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeLobHandler
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#getConfigTimeTransactionManager
*/
public ClobStringType() {
super();
@ -66,7 +66,7 @@ public class ClobStringType extends AbstractLobType {
return new int[] {Types.CLOB};
}
public Class<?> returnedClass() {
public Class returnedClass() {
return String.class;
}

View File

@ -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.
@ -42,21 +42,19 @@ import org.hibernate.persister.entity.EntityPersister;
* calls, with the Hibernate SessionFactory configuration specifying an
* <code>IdTransferringMergeEventListener</code>.
*
* <p>Typically specified as entry for SessionFactoryBuilder's "eventListeners"
* <p>Typically specified as entry for LocalSessionFactoryBean's "eventListeners"
* map, with key "merge".
*
* @author Juergen Hoeller
* @since 1.2
* @see org.springframework.orm.hibernate3.SessionFactoryBuilder#setEventListeners(java.util.Map)
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#setEventListeners(java.util.Map)
*/
@SuppressWarnings("serial")
public class IdTransferringMergeEventListener extends DefaultMergeEventListener {
/**
* Hibernate 3.1 implementation of ID transferral.
*/
@Override
@SuppressWarnings("rawtypes")
protected void entityIsTransient(MergeEvent event, Map copyCache) {
super.entityIsTransient(event, copyCache);
SessionImplementor session = event.getSession();

View File

@ -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.
@ -30,20 +30,18 @@ import org.springframework.aop.support.AopUtils;
*
* <p>Usage example:
*
* <pre class="code">
* {@code
* <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
* <pre>
* &lt;bean id=&quot;sessionFactory&quot; class=&quot;org.springframework.orm.hibernate3.LocalSessionFactoryBean&quot;&gt;
* ...
* <property name="entityInterceptor">
* <bean class="org.springframework.orm.hibernate3.support.ScopedBeanInterceptor"/>
* </property>
* </bean>}</pre>
* &lt;property name=&quot;entityInterceptor&quot;&gt;
* &lt;bean class=&quot;org.springframework.orm.hibernate3.support.ScopedBeanInterceptor&quot;/&gt;
* &lt;/property&gt;
* &lt;/bean&gt;</pre>
*
* @author Costin Leau
* @author Juergen Hoeller
* @since 2.0
*/
@SuppressWarnings("serial")
public class ScopedBeanInterceptor extends EmptyInterceptor {
@Override

View File

@ -117,8 +117,7 @@ public class HibernateTransactionManagerTests extends TestCase {
queryControl.replay();
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
@Override
protected SessionFactory newSessionFactory() throws HibernateException {
protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
return sf;
}
};
@ -340,8 +339,7 @@ public class HibernateTransactionManagerTests extends TestCase {
queryControl.replay();
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
@Override
protected SessionFactory newSessionFactory() throws HibernateException {
protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
return sf;
}
};
@ -418,8 +416,7 @@ public class HibernateTransactionManagerTests extends TestCase {
txControl.replay();
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
@Override
protected SessionFactory newSessionFactory() throws HibernateException {
protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
return sf;
}
};
@ -773,8 +770,7 @@ public class HibernateTransactionManagerTests extends TestCase {
sessionControl.replay();
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
@Override
protected SessionFactory newSessionFactory() throws HibernateException {
protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
return sf;
}
};
@ -858,8 +854,7 @@ public class HibernateTransactionManagerTests extends TestCase {
txControl.replay();
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
@Override
protected SessionFactory newSessionFactory() throws HibernateException {
protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
return sf;
}
};

View File

@ -28,11 +28,9 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.transaction.TransactionManager;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
@ -52,6 +50,7 @@ import org.hibernate.engine.FilterDefinition;
import org.hibernate.event.MergeEvent;
import org.hibernate.event.MergeEventListener;
import org.hibernate.mapping.TypeDef;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
@ -60,17 +59,14 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 05.03.2005
*/
@SuppressWarnings("serial")
public class LocalSessionFactoryBeanTests extends TestCase {
public void testLocalSessionFactoryBeanWithDataSource() throws Exception {
final DriverManagerDataSource ds = new DriverManagerDataSource();
final List invocations = new ArrayList();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration addInputStream(InputStream is) {
@ -84,11 +80,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(LocalDataSourceConnectionProvider.class.getName(),
this.getConfiguration().getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, SessionFactoryBuilderSupport.getConfigTimeDataSource());
config.getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
invocations.add("newSessionFactory");
return null;
}
@ -103,7 +98,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
final RegionFactory regionFactory = new NoCachingRegionFactory(null);
final List invocations = new ArrayList();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration addInputStream(InputStream is) {
@ -117,11 +111,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(LocalRegionFactoryProxy.class.getName(),
this.getConfiguration().getProperty(Environment.CACHE_REGION_FACTORY));
assertSame(regionFactory, SessionFactoryBuilderSupport.getConfigTimeRegionFactory());
config.getProperty(Environment.CACHE_REGION_FACTORY));
assertSame(regionFactory, LocalSessionFactoryBean.getConfigTimeRegionFactory());
invocations.add("newSessionFactory");
return null;
}
@ -132,13 +125,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
assertEquals("newSessionFactory", invocations.get(0));
}
@SuppressWarnings("deprecation")
// CacheProvider is deprecated in Hibernate 3.3, but LSFB still supports its use
public void testLocalSessionFactoryBeanWithCacheProvider() throws Exception {
final CacheProvider cacheProvider = new NoCacheProvider();
final List<String> invocations = new ArrayList<String>();
final List invocations = new ArrayList();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration addInputStream(InputStream is) {
@ -153,11 +143,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(LocalCacheProviderProxy.class.getName(),
this.getConfiguration().getProperty(Environment.CACHE_PROVIDER));
assertSame(cacheProvider, SessionFactoryBeanDelegate.getConfigTimeCacheProvider());
config.getProperty(Environment.CACHE_PROVIDER));
assertSame(cacheProvider, LocalSessionFactoryBean.getConfigTimeCacheProvider());
invocations.add("newSessionFactory");
return null;
}
@ -172,7 +161,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
final DriverManagerDataSource ds = new DriverManagerDataSource();
final List invocations = new ArrayList();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration addInputStream(InputStream is) {
@ -187,11 +175,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(TransactionAwareDataSourceConnectionProvider.class.getName(),
this.getConfiguration().getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, SessionFactoryBuilderSupport.getConfigTimeDataSource());
config.getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
invocations.add("newSessionFactory");
return null;
}
@ -209,7 +196,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
final TransactionManager tm = (TransactionManager) tmControl.getMock();
final List invocations = new ArrayList();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration addInputStream(InputStream is) {
@ -224,14 +210,13 @@ public class LocalSessionFactoryBeanTests extends TestCase {
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(LocalJtaDataSourceConnectionProvider.class.getName(),
this.getConfiguration().getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, SessionFactoryBuilderSupport.getConfigTimeDataSource());
config.getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
assertEquals(LocalTransactionManagerLookup.class.getName(),
this.getConfiguration().getProperty(Environment.TRANSACTION_MANAGER_STRATEGY));
assertEquals(tm, SessionFactoryBuilderSupport.getConfigTimeTransactionManager());
config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY));
assertEquals(tm, LocalSessionFactoryBean.getConfigTimeTransactionManager());
invocations.add("newSessionFactory");
return null;
}
@ -252,7 +237,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
final DriverManagerDataSource ds = new DriverManagerDataSource();
final Set invocations = new HashSet();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration addJar(File file) {
@ -262,11 +246,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(LocalDataSourceConnectionProvider.class.getName(),
this.getConfiguration().getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, SessionFactoryBuilderSupport.getConfigTimeDataSource());
config.getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
invocations.add("newSessionFactory");
return null;
}
@ -285,7 +268,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
final DriverManagerDataSource ds = new DriverManagerDataSource();
final Set invocations = new HashSet();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration addInputStream(InputStream is) {
@ -300,12 +282,11 @@ public class LocalSessionFactoryBeanTests extends TestCase {
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(LocalDataSourceConnectionProvider.class.getName(),
this.getConfiguration().getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, SessionFactoryBuilderSupport.getConfigTimeDataSource());
assertEquals("myValue", this.getConfiguration().getProperty("myProperty"));
config.getProperty(Environment.CONNECTION_PROVIDER));
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
assertEquals("myValue", config.getProperty("myProperty"));
invocations.add("newSessionFactory");
return null;
}
@ -326,11 +307,10 @@ public class LocalSessionFactoryBeanTests extends TestCase {
public void testLocalSessionFactoryBeanWithValidProperties() throws Exception {
final Set invocations = new HashSet();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
assertEquals(UserSuppliedConnectionProvider.class.getName(),
this.getConfiguration().getProperty(Environment.CONNECTION_PROVIDER));
assertEquals("myValue", this.getConfiguration().getProperty("myProperty"));
config.getProperty(Environment.CONNECTION_PROVIDER));
assertEquals("myValue", config.getProperty("myProperty"));
invocations.add("newSessionFactory");
return null;
}
@ -376,8 +356,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
factoryControl.setVoidCallable(1);
factoryControl.replay();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
return sessionFactory;
}
};
@ -392,7 +371,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
public void testLocalSessionFactoryBeanWithEntityInterceptor() throws Exception {
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration setInterceptor(Interceptor interceptor) {
@ -419,7 +397,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
public void testLocalSessionFactoryBeanWithNamingStrategy() throws Exception {
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration setNamingStrategy(NamingStrategy namingStrategy) {
@ -445,7 +422,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
final Properties registeredClassCache = new Properties();
final Properties registeredCollectionCache = new Properties();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public Configuration setCacheConcurrencyStrategy(String clazz, String concurrencyStrategy) {
@ -458,8 +434,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
return null;
}
};
@ -482,7 +457,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
final Properties registeredClassCache = new Properties();
final Properties registeredCollectionCache = new Properties();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
// changed from return type 'void' to 'Configuration' in Hibernate 3.6
@ -494,8 +468,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
return null;
}
};
@ -517,7 +490,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
public void testLocalSessionFactoryBeanWithEventListeners() throws Exception {
final Map registeredListeners = new HashMap();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public void setListener(String type, Object listener) {
@ -525,8 +497,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
return null;
}
};
@ -543,7 +514,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
public void testLocalSessionFactoryBeanWithEventListenerSet() throws Exception {
final Map registeredListeners = new HashMap();
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
@Override
protected Configuration newConfiguration() {
return new Configuration() {
public void setListeners(String type, Object[] listeners) {
@ -552,8 +522,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
}
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
return null;
}
};
@ -610,7 +579,6 @@ public class LocalSessionFactoryBeanTests extends TestCase {
public List registeredFilterDefinitions = new LinkedList();
@Override
protected Configuration newConfiguration() throws HibernateException {
return new Configuration() {
public void addFilterDefinition(FilterDefinition definition) {
@ -619,8 +587,7 @@ public class LocalSessionFactoryBeanTests extends TestCase {
};
}
@Override
protected SessionFactory newSessionFactory() {
protected SessionFactory newSessionFactory(Configuration config) {
return null;
}
}
@ -630,9 +597,8 @@ public class LocalSessionFactoryBeanTests extends TestCase {
public Mappings mappings;
@Override
protected SessionFactory newSessionFactory() {
this.mappings = this.getConfiguration().createMappings();
protected SessionFactory newSessionFactory(Configuration config) {
this.mappings = config.createMappings();
return null;
}
}