HHH-5765 : Wire in connection provider from service registry

This commit is contained in:
Gail Badner 2010-11-30 11:38:53 -08:00
parent de1d2a6247
commit 88543c7a58
87 changed files with 768 additions and 1048 deletions

View File

@ -929,7 +929,7 @@ public interface Session extends Serializable {
* <p/>
* Note that disconnect() called on a session where the connection was
* retrieved by Hibernate through its configured
* {@link org.hibernate.connection.ConnectionProvider} has no effect,
* {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} has no effect,
* provided {@link ConnectionReleaseMode#ON_CLOSE} is not in effect.
*
* @return the application-supplied connection or <tt>null</tt>

View File

@ -57,7 +57,7 @@ public interface SessionFactory extends Referenceable, Serializable {
* Open a {@link Session}.
* <p/>
* JDBC {@link Connection connection(s} will be obtained from the
* configured {@link org.hibernate.connection.ConnectionProvider} as needed
* configured {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} as needed
* to perform requested work.
*
* @return The created session.
@ -70,7 +70,7 @@ public interface SessionFactory extends Referenceable, Serializable {
* Open a {@link Session}, utilizing the specified {@link Interceptor}.
* <p/>
* JDBC {@link Connection connection(s} will be obtained from the
* configured {@link org.hibernate.connection.ConnectionProvider} as needed
* configured {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} as needed
* to perform requested work.
*
* @param interceptor a session-scoped interceptor
@ -87,7 +87,7 @@ public interface SessionFactory extends Referenceable, Serializable {
* Note that the second-level cache will be disabled if you supply a JDBC
* connection. Hibernate will not be able to track any statements you might
* have executed in the same transaction. Consider implementing your own
* {@link org.hibernate.connection.ConnectionProvider} instead as a highly
* {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} instead as a highly
* recommended alternative.
*
* @param connection a connection provided by the application.
@ -103,7 +103,7 @@ public interface SessionFactory extends Referenceable, Serializable {
* Note that the second-level cache will be disabled if you supply a JDBC
* connection. Hibernate will not be able to track any statements you might
* have executed in the same transaction. Consider implementing your own
* {@link org.hibernate.connection.ConnectionProvider} instead as a highly
* {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} instead as a highly
* recommended alternative.
*
* @param connection a connection provided by the application.

View File

@ -74,10 +74,6 @@ public class AnnotationConfiguration extends Configuration {
super();
}
public AnnotationConfiguration(SettingsFactory sf) {
super( sf );
}
/**
* {@inheritDoc}
*/

View File

@ -94,6 +94,7 @@ import org.hibernate.engine.Mapping;
import org.hibernate.engine.NamedQueryDefinition;
import org.hibernate.engine.NamedSQLQueryDefinition;
import org.hibernate.engine.ResultSetMappingDefinition;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.event.AutoFlushEventListener;
import org.hibernate.event.DeleteEventListener;
import org.hibernate.event.DirtyCheckEventListener;
@ -151,6 +152,8 @@ import org.hibernate.mapping.TypeDef;
import org.hibernate.mapping.UniqueKey;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.secure.JACCConfiguration;
import org.hibernate.service.spi.ServicesRegistry;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
import org.hibernate.tool.hbm2ddl.IndexMetadata;
import org.hibernate.tool.hbm2ddl.TableMetadata;
@ -1820,7 +1823,7 @@ public class Configuration implements Serializable {
*
* @throws HibernateException usually indicates an invalid configuration or invalid mapping information
*/
public SessionFactory buildSessionFactory() throws HibernateException {
public SessionFactory buildSessionFactory(ServicesRegistry serviceRegistry) throws HibernateException {
log.debug( "Preparing to build session factory with filters : " + filterDefinitions );
secondPassCompile();
@ -1837,11 +1840,12 @@ public class Configuration implements Serializable {
Properties copy = new Properties();
copy.putAll( properties );
ConfigurationHelper.resolvePlaceHolders( copy );
Settings settings = buildSettings( copy );
Settings settings = buildSettings( copy, serviceRegistry.getService( JdbcServices.class ).getConnectionProvider() );
return new SessionFactoryImpl(
this,
mapping,
serviceRegistry,
settings,
getInitializedEventListeners(),
sessionFactoryObserver
@ -2819,18 +2823,18 @@ public class Configuration implements Serializable {
*
* @return The build settings
*/
public Settings buildSettings() {
public Settings buildSettings(ConnectionProvider connectionProvider) {
Properties clone = ( Properties ) properties.clone();
ConfigurationHelper.resolvePlaceHolders( clone );
return buildSettingsInternal( clone );
return buildSettingsInternal( clone, connectionProvider );
}
public Settings buildSettings(Properties props) throws HibernateException {
return buildSettingsInternal( props );
public Settings buildSettings(Properties props, ConnectionProvider connectionProvider) throws HibernateException {
return buildSettingsInternal( props, connectionProvider );
}
private Settings buildSettingsInternal(Properties props) {
final Settings settings = settingsFactory.buildSettings( props );
private Settings buildSettingsInternal(Properties props, ConnectionProvider connectionProvider) {
final Settings settings = settingsFactory.buildSettings( props, connectionProvider );
settings.setEntityTuplizerFactory( this.getEntityTuplizerFactory() );
// settings.setComponentTuplizerFactory( this.getComponentTuplizerFactory() );
return settings;

View File

@ -82,7 +82,7 @@ import org.hibernate.util.ConfigHelper;
* </tr>
* <tr>
* <td><tt>hibernate.connection.provider_class</tt></td>
* <td>classname of <tt>org.hibernate.connection.ConnectionProvider</tt>
* <td>classname of <tt>org.hibernate.service.jdbc.connections.spi.ConnectionProvider</tt>
* subclass (if not specified hueristics are used)</td>
* </tr>
* <tr><td><tt>hibernate.connection.username</tt></td><td>database username</td></tr>

View File

@ -29,7 +29,7 @@ import org.hibernate.ConnectionReleaseMode;
import org.hibernate.EntityMode;
import org.hibernate.cache.QueryCacheFactory;
import org.hibernate.cache.RegionFactory;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.JdbcSupport;
import org.hibernate.exception.SQLExceptionConverter;
@ -172,10 +172,6 @@ public final class Settings {
return jdbcFetchSize;
}
public ConnectionProvider getConnectionProvider() {
return connectionProvider;
}
public TransactionFactory getTransactionFactory() {
return transactionFactory;
}

View File

@ -43,8 +43,7 @@ import org.hibernate.cache.QueryCacheFactory;
import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.impl.NoCachingRegionFactory;
import org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.ConnectionProviderFactory;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.resolver.DialectFactory;
import org.hibernate.exception.SQLExceptionConverter;
@ -76,7 +75,7 @@ public class SettingsFactory implements Serializable {
protected SettingsFactory() {
}
public Settings buildSettings(Properties props) {
public Settings buildSettings(Properties props, ConnectionProvider connections) {
Settings settings = new Settings();
//SessionFactory name:
@ -86,9 +85,6 @@ public class SettingsFactory implements Serializable {
//JDBC and connection settings:
ConnectionProvider connections = createConnectionProvider(props);
settings.setConnectionProvider(connections);
//Interrogate JDBC metadata
boolean metaSupportsScrollable = false;
@ -449,10 +445,6 @@ public class SettingsFactory implements Serializable {
}
}
protected ConnectionProvider createConnectionProvider(Properties properties) {
return ConnectionProviderFactory.newConnectionProvider(properties);
}
protected TransactionFactory createTransactionFactory(Properties properties) {
return TransactionFactoryFactory.buildTransactionFactory(properties);
}

View File

@ -1,94 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.connection;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
/**
* A strategy for obtaining JDBC connections.
* <br><br>
* Implementors might also implement connection pooling.<br>
* <br>
* The <tt>ConnectionProvider</tt> interface is not intended to be
* exposed to the application. Instead it is used internally by
* Hibernate to obtain connections.<br>
* <br>
* Implementors should provide a public default constructor.
*
* @see ConnectionProviderFactory
* @author Gavin King
*/
public interface ConnectionProvider {
/**
* Initialize the connection provider from given properties.
* @param props <tt>SessionFactory</tt> properties
*/
public void configure(Properties props) throws HibernateException;
/**
* Grab a connection, with the autocommit mode specified by
* <tt>hibernate.connection.autocommit</tt>.
* @return a JDBC connection
* @throws SQLException
*/
public Connection getConnection() throws SQLException;
/**
* Dispose of a used connection.
* @param conn a JDBC connection
* @throws SQLException
*/
public void closeConnection(Connection conn) throws SQLException;
/**
* Release all resources held by this provider. JavaDoc requires a second sentence.
* @throws HibernateException
*/
public void close() throws HibernateException;
/**
* Does this connection provider support aggressive release of JDBC
* connections and re-acquistion of those connections (if need be) later?
* <p/>
* This is used in conjunction with {@link org.hibernate.cfg.Environment.RELEASE_CONNECTIONS}
* to aggressively release JDBC connections. However, the configured ConnectionProvider
* must support re-acquisition of the same underlying connection for that semantic to work.
* <p/>
* Typically, this is only true in managed environments where a container
* tracks connections by transaction or thread.
*
* Note that JTA semantic depends on the fact that the underlying connection provider does
* support aggressive release.
*/
public boolean supportsAggressiveRelease();
}

View File

@ -1,235 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.connection;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.util.ReflectHelper;
/**
* Instantiates a connection provider given either <tt>System</tt> properties or
* a <tt>java.util.Properties</tt> instance. The <tt>ConnectionProviderFactory</tt>
* first attempts to find a name of a <tt>ConnectionProvider</tt> subclass in the
* property <tt>hibernate.connection.provider_class</tt>. If missing, heuristics are used
* to choose either <tt>DriverManagerConnectionProvider</tt>,
* <tt>DatasourceConnectionProvider</tt>, <tt>C3P0ConnectionProvider</tt> or
* <tt>DBCPConnectionProvider</tt>.
*
* @author Gavin King
* @see ConnectionProvider
*/
public final class ConnectionProviderFactory {
private static final Logger log = LoggerFactory.getLogger( ConnectionProviderFactory.class );
/**
* Instantiate a <tt>ConnectionProvider</tt> using <tt>System</tt> properties.
*
* @return The created connection provider.
*
* @throws HibernateException
*/
public static ConnectionProvider newConnectionProvider() throws HibernateException {
return newConnectionProvider( Environment.getProperties() );
}
/**
* Instantiate a <tt>ConnectionProvider</tt> using given properties.
* Method newConnectionProvider.
*
* @param properties hibernate <tt>SessionFactory</tt> properties
*
* @return ConnectionProvider
*
* @throws HibernateException
*/
public static ConnectionProvider newConnectionProvider(Properties properties) throws HibernateException {
return newConnectionProvider( properties, null );
}
/**
* Create a connection provider based on the given information.
*
* @param properties Properties being used to build the {@link org.hibernate.SessionFactory}.
* @param connectionProviderInjectionData Something to be injected in the connection provided
*
* @return The created connection provider
*
* @throws HibernateException
*/
public static ConnectionProvider newConnectionProvider(Properties properties, Map connectionProviderInjectionData)
throws HibernateException {
ConnectionProvider connections;
String providerClass = properties.getProperty( Environment.CONNECTION_PROVIDER );
if ( providerClass != null ) {
connections = initializeConnectionProviderFromConfig( providerClass );
}
else if ( c3p0ConfigDefined( properties ) && c3p0ProviderPresent() ) {
connections = initializeConnectionProviderFromConfig("org.hibernate.connection.C3P0ConnectionProvider");
}
else if ( properties.getProperty( Environment.DATASOURCE ) != null ) {
connections = new DatasourceConnectionProvider();
}
else if ( properties.getProperty( Environment.URL ) != null ) {
connections = new DriverManagerConnectionProvider();
}
else {
connections = new UserSuppliedConnectionProvider();
}
if ( connectionProviderInjectionData != null && connectionProviderInjectionData.size() != 0 ) {
//inject the data
try {
BeanInfo info = Introspector.getBeanInfo( connections.getClass() );
PropertyDescriptor[] descritors = info.getPropertyDescriptors();
int size = descritors.length;
for ( int index = 0; index < size; index++ ) {
String propertyName = descritors[index].getName();
if ( connectionProviderInjectionData.containsKey( propertyName ) ) {
Method method = descritors[index].getWriteMethod();
method.invoke(
connections, new Object[] { connectionProviderInjectionData.get( propertyName ) }
);
}
}
}
catch ( IntrospectionException e ) {
throw new HibernateException( "Unable to inject objects into the connection provider", e );
}
catch ( IllegalAccessException e ) {
throw new HibernateException( "Unable to inject objects into the connection provider", e );
}
catch ( InvocationTargetException e ) {
throw new HibernateException( "Unable to inject objects into the connection provider", e );
}
}
connections.configure( properties );
return connections;
}
private static boolean c3p0ProviderPresent() {
try {
ReflectHelper.classForName( "org.hibernate.connection.C3P0ConnectionProvider" );
}
catch ( ClassNotFoundException e ) {
log.warn( "c3p0 properties is specificed, but could not find org.hibernate.connection.C3P0ConnectionProvider from the classpath, " +
"these properties are going to be ignored." );
return false;
}
return true;
}
private static boolean c3p0ConfigDefined(Properties properties) {
Iterator iter = properties.keySet().iterator();
while ( iter.hasNext() ) {
String property = (String) iter.next();
if ( property.startsWith( "hibernate.c3p0" ) ) {
return true;
}
}
return false;
}
private static ConnectionProvider initializeConnectionProviderFromConfig(String providerClass) {
ConnectionProvider connections;
try {
log.info( "Initializing connection provider: " + providerClass );
connections = (ConnectionProvider) ReflectHelper.classForName( providerClass ).newInstance();
}
catch ( Exception e ) {
log.error( "Could not instantiate connection provider", e );
throw new HibernateException( "Could not instantiate connection provider: " + providerClass );
}
return connections;
}
// cannot be instantiated
private ConnectionProviderFactory() {
throw new UnsupportedOperationException();
}
/**
* Transform JDBC connection properties.
*
* Passed in the form <tt>hibernate.connection.*</tt> to the
* format accepted by <tt>DriverManager</tt> by trimming the leading "<tt>hibernate.connection</tt>".
*/
public static Properties getConnectionProperties(Properties properties) {
Iterator iter = properties.keySet().iterator();
Properties result = new Properties();
while ( iter.hasNext() ) {
String prop = (String) iter.next();
if ( prop.startsWith( Environment.CONNECTION_PREFIX ) && !SPECIAL_PROPERTIES.contains( prop ) ) {
result.setProperty(
prop.substring( Environment.CONNECTION_PREFIX.length() + 1 ),
properties.getProperty( prop )
);
}
}
String userName = properties.getProperty( Environment.USER );
if ( userName != null ) {
result.setProperty( "user", userName );
}
return result;
}
private static final Set SPECIAL_PROPERTIES;
static {
SPECIAL_PROPERTIES = new HashSet();
SPECIAL_PROPERTIES.add( Environment.DATASOURCE );
SPECIAL_PROPERTIES.add( Environment.URL );
SPECIAL_PROPERTIES.add( Environment.CONNECTION_PROVIDER );
SPECIAL_PROPERTIES.add( Environment.POOL_SIZE );
SPECIAL_PROPERTIES.add( Environment.ISOLATION );
SPECIAL_PROPERTIES.add( Environment.DRIVER );
SPECIAL_PROPERTIES.add( Environment.USER );
}
}

View File

@ -1,116 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.connection;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.internal.util.jndi.JndiHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A connection provider that uses a <tt>DataSource</tt> registered with JNDI.
* Hibernate will use this <tt>ConnectionProvider</tt> by default if the
* property <tt>hibernate.connection.datasource</tt> is set.
* @see ConnectionProvider
* @author Gavin King
*/
public class DatasourceConnectionProvider implements ConnectionProvider {
private DataSource ds;
private String user;
private String pass;
private static final Logger log = LoggerFactory.getLogger(DatasourceConnectionProvider.class);
public DataSource getDataSource() {
return ds;
}
public void setDataSource(DataSource ds) {
this.ds = ds;
}
public void configure(Properties props) throws HibernateException {
String jndiName = props.getProperty( Environment.DATASOURCE );
if ( jndiName == null ) {
String msg = "datasource JNDI name was not specified by property " + Environment.DATASOURCE;
log.error( msg );
throw new HibernateException( msg );
}
user = props.getProperty( Environment.USER );
pass = props.getProperty( Environment.PASS );
try {
ds = ( DataSource ) JndiHelper.getInitialContext( props ).lookup( jndiName );
}
catch ( Exception e ) {
log.error( "Could not find datasource: " + jndiName, e );
throw new HibernateException( "Could not find datasource", e );
}
if ( ds == null ) {
throw new HibernateException( "Could not find datasource: " + jndiName );
}
log.info( "Using datasource: " + jndiName );
}
public Connection getConnection() throws SQLException {
if (user != null || pass != null) {
return ds.getConnection(user, pass);
}
else {
return ds.getConnection();
}
}
public void closeConnection(Connection conn) throws SQLException {
conn.close();
}
public void close() {}
/**
* @see ConnectionProvider#supportsAggressiveRelease()
*/
public boolean supportsAggressiveRelease() {
return true;
}
}

View File

@ -1,199 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.util.ReflectHelper;
/**
* A connection provider that uses <tt>java.sql.DriverManager</tt>. This provider
* also implements a very rudimentary connection pool.
* @see ConnectionProvider
* @author Gavin King
*/
public class DriverManagerConnectionProvider implements ConnectionProvider {
private String url;
private Properties connectionProps;
private Integer isolation;
private final ArrayList pool = new ArrayList();
private int poolSize;
private int checkedOut = 0;
private boolean autocommit;
private static final Logger log = LoggerFactory.getLogger(DriverManagerConnectionProvider.class);
public void configure(Properties props) throws HibernateException {
String driverClass = props.getProperty(Environment.DRIVER);
poolSize = ConfigurationHelper.getInt(Environment.POOL_SIZE, props, 20); //default pool size 20
log.info("Using Hibernate built-in connection pool (not for production use!)");
log.info("Hibernate connection pool size: " + poolSize);
autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, props);
log.info("autocommit mode: " + autocommit);
isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, props);
if (isolation!=null)
log.info( "JDBC isolation level: " + Environment.isolationLevelToString( isolation.intValue() ) );
if (driverClass==null) {
log.warn("no JDBC Driver class was specified by property " + Environment.DRIVER);
}
else {
try {
// trying via forName() first to be as close to DriverManager's semantics
Class.forName(driverClass);
}
catch (ClassNotFoundException cnfe) {
try {
ReflectHelper.classForName(driverClass);
}
catch (ClassNotFoundException e) {
String msg = "JDBC Driver class not found: " + driverClass;
log.error( msg, e );
throw new HibernateException(msg, e);
}
}
}
url = props.getProperty( Environment.URL );
if ( url == null ) {
String msg = "JDBC URL was not specified by property " + Environment.URL;
log.error( msg );
throw new HibernateException( msg );
}
connectionProps = ConnectionProviderFactory.getConnectionProperties( props );
log.info( "using driver: " + driverClass + " at URL: " + url );
// if debug level is enabled, then log the password, otherwise mask it
if ( log.isDebugEnabled() ) {
log.info( "connection properties: " + connectionProps );
}
else if ( log.isInfoEnabled() ) {
log.info( "connection properties: " + ConfigurationHelper.maskOut(connectionProps, "password") );
}
}
public Connection getConnection() throws SQLException {
if ( log.isTraceEnabled() ) log.trace( "total checked-out connections: " + checkedOut );
synchronized (pool) {
if ( !pool.isEmpty() ) {
int last = pool.size() - 1;
if ( log.isTraceEnabled() ) {
log.trace("using pooled JDBC connection, pool size: " + last);
checkedOut++;
}
Connection pooled = (Connection) pool.remove(last);
if (isolation!=null) pooled.setTransactionIsolation( isolation.intValue() );
if ( pooled.getAutoCommit()!=autocommit ) pooled.setAutoCommit(autocommit);
return pooled;
}
}
log.debug("opening new JDBC connection");
Connection conn = DriverManager.getConnection(url, connectionProps);
if (isolation!=null) conn.setTransactionIsolation( isolation.intValue() );
if ( conn.getAutoCommit()!=autocommit ) conn.setAutoCommit(autocommit);
if ( log.isDebugEnabled() ) {
log.debug( "created connection to: " + url + ", Isolation Level: " + conn.getTransactionIsolation() );
}
if ( log.isTraceEnabled() ) checkedOut++;
return conn;
}
public void closeConnection(Connection conn) throws SQLException {
if ( log.isDebugEnabled() ) checkedOut--;
synchronized (pool) {
int currentSize = pool.size();
if ( currentSize < poolSize ) {
if ( log.isTraceEnabled() ) log.trace("returning connection to pool, pool size: " + (currentSize + 1) );
pool.add(conn);
return;
}
}
log.debug("closing JDBC connection");
conn.close();
}
protected void finalize() {
close();
}
public void close() {
log.info("cleaning up connection pool: " + url);
Iterator iter = pool.iterator();
while ( iter.hasNext() ) {
try {
( (Connection) iter.next() ).close();
}
catch (SQLException sqle) {
log.warn("problem closing pooled connection", sqle);
}
}
pool.clear();
}
/**
* @see ConnectionProvider#supportsAggressiveRelease()
*/
public boolean supportsAggressiveRelease() {
return false;
}
}

View File

@ -1,80 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.connection;
import java.sql.Connection;
import java.util.Properties;
import org.slf4j.LoggerFactory;
import org.hibernate.HibernateException;
/**
* An implementation of the <literal>ConnectionProvider</literal> interface that
* simply throws an exception when a connection is requested. This implementation
* indicates that the user is expected to supply a JDBC connection.
* @see ConnectionProvider
* @author Gavin King
*/
public class UserSuppliedConnectionProvider implements ConnectionProvider {
/**
* @see org.hibernate.connection.ConnectionProvider#configure(Properties)
*/
public void configure(Properties props) throws HibernateException {
LoggerFactory.getLogger( UserSuppliedConnectionProvider.class )
.warn( "No connection properties specified - the user must supply JDBC connections" );
}
/**
* @see org.hibernate.connection.ConnectionProvider#getConnection()
*/
public Connection getConnection() {
throw new UnsupportedOperationException("The user must supply a JDBC connection");
}
/**
* @see org.hibernate.connection.ConnectionProvider#closeConnection(Connection)
*/
public void closeConnection(Connection conn) {
throw new UnsupportedOperationException("The user must supply a JDBC connection");
}
public void close() {
}
/**
* @see ConnectionProvider#supportsAggressiveRelease()
*/
public boolean supportsAggressiveRelease() {
return false;
}
}

View File

@ -1,38 +0,0 @@
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
~ indicated by the @author tags or express copyright attribution
~ statements applied by the authors. All third-party contributions are
~ distributed under license by Red Hat Middleware LLC.
~
~ This copyrighted material is made available to anyone wishing to use, modify,
~ copy, or redistribute it subject to the terms and conditions of the GNU
~ Lesser General Public License, as published by the Free Software Foundation.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this distribution; if not, write to:
~ Free Software Foundation, Inc.
~ 51 Franklin Street, Fifth Floor
~ Boston, MA 02110-1301 USA
~
-->
<html>
<head></head>
<body>
<p>
This package abstracts the mechanism for obtaining
a JDBC connection.
</p>
<p>
A concrete implementation of <tt>ConnectionProvider</tt> may be
selected by specifying <tt>hibernate.connection.provider_class</tt>.
</p>
</body>
</html>

View File

@ -45,7 +45,7 @@ import org.hibernate.cache.QueryCache;
import org.hibernate.cache.UpdateTimestampsCache;
import org.hibernate.cache.Region;
import org.hibernate.cfg.Settings;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.SQLFunctionRegistry;
import org.hibernate.exception.SQLExceptionConverter;

View File

@ -74,7 +74,8 @@ import org.hibernate.cache.impl.CacheDataDescriptionImpl;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.Settings;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.context.CurrentSessionContext;
import org.hibernate.context.JTASessionContext;
import org.hibernate.context.ManagedSessionContext;
@ -110,6 +111,7 @@ import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.Queryable;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.service.spi.ServicesRegistry;
import org.hibernate.stat.ConcurrentStatisticsImpl;
import org.hibernate.stat.Statistics;
import org.hibernate.stat.StatisticsImplementor;
@ -142,7 +144,7 @@ import org.hibernate.util.ReflectHelper;
* and pooling under the covers. It is crucial that the class is not only thread
* safe, but also highly concurrent. Synchronization must be used extremely sparingly.
*
* @see org.hibernate.connection.ConnectionProvider
* @see org.hibernate.service.jdbc.connections.spi.ConnectionProvider
* @see org.hibernate.classic.Session
* @see org.hibernate.hql.QueryTranslator
* @see org.hibernate.persister.entity.EntityPersister
@ -170,6 +172,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI
private final transient Map fetchProfiles;
private final transient Map imports;
private final transient Interceptor interceptor;
private final transient ServicesRegistry serviceRegistry;
private final transient Settings settings;
private final transient Properties properties;
private transient SchemaExport schemaExport;
@ -194,6 +197,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI
public SessionFactoryImpl(
Configuration cfg,
Mapping mapping,
ServicesRegistry serviceRegistry,
Settings settings,
EventListeners listeners,
SessionFactoryObserver observer) throws HibernateException {
@ -206,6 +210,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI
this.properties = new Properties();
this.properties.putAll( cfg.getProperties() );
this.interceptor = cfg.getInterceptor();
this.serviceRegistry = serviceRegistry;
this.settings = settings;
this.sqlFunctionRegistry = new SQLFunctionRegistry(settings.getDialect(), cfg.getSqlFunctions());
this.eventListeners = listeners;
@ -367,16 +372,16 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI
log.debug("instantiated session factory");
if ( settings.isAutoCreateSchema() ) {
new SchemaExport( cfg, settings ).create( false, true );
new SchemaExport( getJdbcServices(), cfg ).create( false, true );
}
if ( settings.isAutoUpdateSchema() ) {
new SchemaUpdate( cfg, settings ).execute( false, true );
new SchemaUpdate( getJdbcServices(), cfg ).execute( false, true );
}
if ( settings.isAutoValidateSchema() ) {
new SchemaValidator( cfg, settings ).validate();
new SchemaValidator( getJdbcServices(), cfg ).validate();
}
if ( settings.isAutoDropSchema() ) {
schemaExport = new SchemaExport( cfg, settings );
schemaExport = new SchemaExport( getJdbcServices(), cfg );
}
if ( settings.getTransactionManagerLookup()!=null ) {
@ -897,8 +902,12 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI
return getEntityPersister(className).getPropertyType(propertyName);
}
private JdbcServices getJdbcServices() {
return serviceRegistry.getService( JdbcServices.class );
}
public ConnectionProvider getConnectionProvider() {
return settings.getConnectionProvider();
return serviceRegistry.getService( JdbcServices.class ).getConnectionProvider();
}
/**
@ -959,12 +968,7 @@ public final class SessionFactoryImpl implements SessionFactory, SessionFactoryI
schemaExport.drop( false, true );
}
try {
settings.getConnectionProvider().close();
}
finally {
SessionFactoryObjectFactory.removeInstance(uuid, name, properties);
}
SessionFactoryObjectFactory.removeInstance(uuid, name, properties);
observer.sessionFactoryClosed( this );
eventListeners.destroyListeners();

View File

@ -12,6 +12,8 @@ import org.slf4j.LoggerFactory;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.internal.ServicesRegistryBootstrap;
import org.hibernate.service.spi.ServicesRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.internal.util.jndi.JndiHelper;
import org.hibernate.util.ExternalSessionFactoryConfig;
@ -33,7 +35,6 @@ public class HibernateService extends ExternalSessionFactoryConfig implements Hi
private String boundName;
private Properties properties = new Properties();
public void start() throws HibernateException {
boundName = getJndiName();
try {
@ -61,7 +62,9 @@ public class HibernateService extends ExternalSessionFactoryConfig implements Hi
SessionFactory buildSessionFactory() throws HibernateException {
log.info( "starting service at JNDI name: " + boundName );
log.info( "service properties: " + properties );
return buildConfiguration().buildSessionFactory();
return buildConfiguration().buildSessionFactory(
new ServicesRegistryBootstrap().initiateServicesRegistry( properties )
);
}
protected Map getExtraProperties() {

View File

@ -255,7 +255,7 @@ public class ConnectionProviderInitiator implements ServiceInitiator<ConnectionP
public static Properties getConnectionProperties(Map<?,?> properties) {
Properties result = new Properties();
for ( Map.Entry entry : properties.entrySet() ) {
if ( ! ( String.class.isInstance( entry.getKey() ) ) && String.class.isInstance( entry.getValue() ) ) {
if ( ! ( String.class.isInstance( entry.getKey() ) ) || ! String.class.isInstance( entry.getValue() ) ) {
continue;
}
final String key = (String) entry.getKey();

View File

@ -46,7 +46,7 @@ public interface StatisticsImplementor {
public void flush();
/**
* Callback about a connection being obtained from {@link org.hibernate.connection.ConnectionProvider}
* Callback about a connection being obtained from {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider}
*/
public void connect();

View File

@ -24,8 +24,8 @@
*/
package org.hibernate.tool.hbm2ddl;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.ConnectionProviderFactory;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.util.JDBCExceptionReporter;
import java.util.Properties;
@ -48,12 +48,14 @@ class ManagedProviderConnectionHelper implements ConnectionHelper {
}
public void prepare(boolean needsAutoCommit) throws SQLException {
connectionProvider = ConnectionProviderFactory.newConnectionProvider( cfgProperties );
/* TEMP TEMP TEMP
connectionProvider = ConnectionProviderBuilder.buildConnectionProvider();
connection = connectionProvider.getConnection();
if ( needsAutoCommit && !connection.getAutoCommit() ) {
connection.commit();
connection.setAutoCommit( true );
}
*/
}
public Connection getConnection() throws SQLException {
@ -67,7 +69,10 @@ class ManagedProviderConnectionHelper implements ConnectionHelper {
connectionProvider.closeConnection( connection );
}
finally {
connectionProvider.close();
if ( connectionProvider instanceof Stoppable ) {
( ( Stoppable ) connectionProvider ).stop();
}
connectionProvider = null;
}
}
connection = null;

View File

@ -49,12 +49,12 @@ import org.hibernate.JDBCException;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.Settings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.jdbc.spi.SQLStatementLogger;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.jdbc.util.FormatStyle;
import org.hibernate.jdbc.util.Formatter;
import org.hibernate.jdbc.util.SQLStatementLogger;
import org.hibernate.util.ConfigHelper;
import org.hibernate.util.JDBCExceptionReporter;
import org.hibernate.util.ReflectHelper;
@ -99,14 +99,17 @@ public class SchemaExport {
* @param settings The 'parsed' settings.
* @throws HibernateException Indicates problem preparing for schema export.
*/
public SchemaExport(Configuration cfg, Settings settings) throws HibernateException {
dialect = settings.getDialect();
connectionHelper = new SuppliedConnectionProviderConnectionHelper( settings.getConnectionProvider() );
public SchemaExport(JdbcServices jdbcServices, Configuration cfg) throws HibernateException {
dialect = jdbcServices.getDialect();
connectionHelper = new SuppliedConnectionProviderConnectionHelper( jdbcServices.getConnectionProvider() );
dropSQL = cfg.generateDropSchemaScript( dialect );
createSQL = cfg.generateSchemaCreationScript( dialect );
sqlStatementLogger = settings.getSqlStatementLogger();
formatter = ( sqlStatementLogger.isFormatSql() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
importFiles = settings.getImportFiles() != null ? settings.getImportFiles() : DEFAULT_IMPORT_FILE;
sqlStatementLogger = jdbcServices.getSqlStatementLogger();
formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
importFiles = ConfigurationHelper.getString(
Environment.HBM2DDL_IMPORT_FILES, cfg.getProperties(),
DEFAULT_IMPORT_FILE
);
}
/**

View File

@ -41,9 +41,10 @@ import org.hibernate.cfg.Environment;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.Settings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.jdbc.util.FormatStyle;
import org.hibernate.jdbc.util.Formatter;
import org.hibernate.jdbc.util.SQLStatementLogger;
import org.hibernate.engine.jdbc.spi.SQLStatementLogger;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.util.ReflectHelper;
import org.slf4j.Logger;
@ -84,15 +85,15 @@ public class SchemaUpdate {
formatter = ( ConfigurationHelper.getBoolean( Environment.FORMAT_SQL, props ) ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
}
public SchemaUpdate(Configuration cfg, Settings settings) throws HibernateException {
public SchemaUpdate(JdbcServices jdbcServices, Configuration cfg) throws HibernateException {
this.configuration = cfg;
dialect = settings.getDialect();
dialect = jdbcServices.getDialect();
connectionHelper = new SuppliedConnectionProviderConnectionHelper(
settings.getConnectionProvider()
jdbcServices.getConnectionProvider()
);
exceptions = new ArrayList();
sqlStatementLogger = settings.getSqlStatementLogger();
formatter = ( sqlStatementLogger.isFormatSql() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
sqlStatementLogger = jdbcServices.getSqlStatementLogger();
formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
}
public static void main(String[] args) {

View File

@ -36,6 +36,7 @@ import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.Settings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.util.ReflectHelper;
/**
@ -64,11 +65,11 @@ public class SchemaValidator {
connectionHelper = new ManagedProviderConnectionHelper( props );
}
public SchemaValidator(Configuration cfg, Settings settings) throws HibernateException {
public SchemaValidator(JdbcServices jdbcServices, Configuration cfg ) throws HibernateException {
this.configuration = cfg;
dialect = settings.getDialect();
dialect = jdbcServices.getDialect();
connectionHelper = new SuppliedConnectionProviderConnectionHelper(
settings.getConnectionProvider()
jdbcServices.getConnectionProvider()
);
}

View File

@ -24,7 +24,7 @@
*/
package org.hibernate.tool.hbm2ddl;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.util.JDBCExceptionReporter;
import java.sql.Connection;

View File

@ -24,8 +24,10 @@
*/
package org.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.internal.ServicesRegistryBootstrap;
import org.hibernate.internal.util.config.ConfigurationHelper;
import java.util.Properties;

View File

@ -40,7 +40,7 @@ Note that there is a large degree of crossover between the notion of extension p
Hibernate provides a number of SPIs intended to integrate itself with various third party frameworks or application code to provide
additional capabilities. The SPIs fall mainly into 2 categories:<ul>
<li>Caching - {@link org.hibernate.cache.RegionFactory}</li>
<li>JDBC Connection management - {@link org.hibernate.connection.ConnectionProvider}
<li>JDBC Connection management - {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider}
</ul>
Certainly {@link org.hibernate.dialect.Dialect} could fit in here as well, though we chose to list it under extensions since application
developers tend to provide extended dialects rather frequently for various reasons.

View File

@ -28,6 +28,8 @@ import java.util.Properties;
import junit.framework.TestCase;
import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator;
/**
* Undocumented
*
@ -46,7 +48,7 @@ public class PropertiesTest extends TestCase {
props.put("rpt.6.hibernate.connection.password_enc", "76f271db3661fd50082e68d4b953fbee");
props.put("hibernate.connection.create", "true");
final Properties outputProps = ConnectionProviderFactory.getConnectionProperties(props);
final Properties outputProps = ConnectionProviderInitiator.getConnectionProperties( props );
assertEquals(1, outputProps.size());
assertEquals("true", outputProps.get("create"));
}

View File

@ -44,7 +44,8 @@ import org.hibernate.impl.SessionImpl;
import org.hibernate.jdbc.Work;
import org.hibernate.mapping.SimpleAuxiliaryDatabaseObject;
import org.hibernate.TestingDatabaseInfo;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this
* unit test so that we can make sure the value keep being generated in the expected manner
@ -56,6 +57,7 @@ public class SequenceHiLoGeneratorNoIncrementTest extends TestCase {
private static final String TEST_SEQUENCE = "test_sequence";
private Configuration cfg;
ServiceRegistryHolder serviceRegistryHolder;
private SessionFactoryImplementor sessionFactory;
private SequenceHiLoGenerator generator;
@ -95,7 +97,8 @@ public class SequenceHiLoGeneratorNoIncrementTest extends TestCase {
)
);
sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() );
sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
@Override
@ -103,7 +106,9 @@ public class SequenceHiLoGeneratorNoIncrementTest extends TestCase {
if ( sessionFactory != null ) {
sessionFactory.close();
}
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
super.tearDown();
}

View File

@ -44,6 +44,7 @@ import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.impl.SessionImpl;
import org.hibernate.jdbc.Work;
import org.hibernate.mapping.SimpleAuxiliaryDatabaseObject;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this
@ -56,6 +57,7 @@ public class SequenceHiLoGeneratorTest extends TestCase {
private static final String TEST_SEQUENCE = "test_sequence";
private Configuration cfg;
private ServiceRegistryHolder serviceRegistryHolder;
private SessionFactoryImplementor sessionFactory;
private SequenceHiLoGenerator generator;
@ -94,8 +96,10 @@ public class SequenceHiLoGeneratorTest extends TestCase {
generator.sqlDropStrings( dialect )[0]
)
);
serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() );
sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory();
sessionFactory =
(SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
@Override
@ -103,7 +107,9 @@ public class SequenceHiLoGeneratorTest extends TestCase {
if ( sessionFactory != null ) {
sessionFactory.close();
}
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
super.tearDown();
}

View File

@ -44,6 +44,7 @@ import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.impl.SessionImpl;
import org.hibernate.jdbc.Work;
import org.hibernate.mapping.SimpleAuxiliaryDatabaseObject;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this
@ -57,6 +58,7 @@ public class TableHiLoGeneratorTest extends TestCase {
private static final String GEN_COLUMN = TableHiLoGenerator.DEFAULT_COLUMN_NAME;
private Configuration cfg;
private ServiceRegistryHolder serviceRegistryHolder;
private SessionFactoryImplementor sessionFactory;
private TableHiLoGenerator generator;
@ -104,7 +106,9 @@ public class TableHiLoGeneratorTest extends TestCase {
)
);
sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() );
sessionFactory =
(SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
@Override
@ -112,6 +116,9 @@ public class TableHiLoGeneratorTest extends TestCase {
if ( sessionFactory != null ) {
sessionFactory.close();
}
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
super.tearDown();
}

View File

@ -28,6 +28,7 @@ import junit.framework.TestCase;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* TODO : javadoc
@ -39,6 +40,8 @@ public class SubclassProxyInterfaceTest extends TestCase {
final Configuration cfg = new Configuration()
.setProperty( Environment.DIALECT, H2Dialect.class.getName() );
cfg.addClass( Person.class );
cfg.buildSessionFactory().close();
ServiceRegistryHolder serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() );
cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() ).close();
serviceRegistryHolder.destroy();
}
}

View File

@ -10,16 +10,29 @@ import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* @author Emmanuel Bernard
*/
public class ConfigurationTest extends junit.framework.TestCase {
private ServiceRegistryHolder serviceRegistryHolder;
protected void setUp() {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
protected void tearDown() {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
public void testDeclarativeMix() throws Exception {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
SessionFactory sf = cfg.buildSessionFactory();
SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
assertNotNull( sf );
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
@ -37,7 +50,7 @@ public class ConfigurationTest extends junit.framework.TestCase {
cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
cfg.setProperty( AnnotationConfiguration.ARTEFACT_PROCESSING_ORDER, "class" );
SessionFactory sf = cfg.buildSessionFactory();
SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
assertNotNull( sf );
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
@ -61,7 +74,7 @@ public class ConfigurationTest extends junit.framework.TestCase {
cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
cfg.addAnnotatedClass( Boat.class );
SessionFactory sf = cfg.buildSessionFactory();
SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
assertNotNull( sf );
Session s = sf.openSession();
s.getTransaction().begin();
@ -87,7 +100,7 @@ public class ConfigurationTest extends junit.framework.TestCase {
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
cfg.setProperty( AnnotationConfiguration.ARTEFACT_PROCESSING_ORDER, "class, hbm" );
cfg.addAnnotatedClass( Boat.class );
SessionFactory sf = cfg.buildSessionFactory();
SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
assertNotNull( sf );
Session s = sf.openSession();
s.getTransaction().begin();
@ -111,7 +124,7 @@ public class ConfigurationTest extends junit.framework.TestCase {
cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
cfg.addClass( Ferry.class );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
SessionFactory sf = cfg.buildSessionFactory();
SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
assertNotNull( sf );
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
@ -129,7 +142,7 @@ public class ConfigurationTest extends junit.framework.TestCase {
cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
cfg.addAnnotatedClass( Port.class );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
SessionFactory sf = cfg.buildSessionFactory();
SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
assertNotNull( sf );
Session s = sf.openSession();
Transaction tx = s.beginTransaction();

View File

@ -5,6 +5,7 @@ import org.hibernate.AnnotationException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* @author Emmanuel Bernard
@ -14,12 +15,19 @@ public class SafeMappingTest extends junit.framework.TestCase {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass( IncorrectEntity.class );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
ServiceRegistryHolder serviceRegistryHolder = null;
try {
SessionFactory sf = cfg.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() );
SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail( "Entity wo id should fail" );
}
catch (AnnotationException e) {
//success
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
}

View File

@ -8,6 +8,7 @@ import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* @author Emmanuel Bernard
@ -30,14 +31,21 @@ public class SecuredBindingTest extends TestCase {
ac.setProperties( p );
ac.addAnnotatedClass( Plane.class );
SessionFactory sf;
ServiceRegistryHolder serviceRegistryHolder = null;
try {
sf = ac.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( p );
sf = ac.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail( "Driver property overriding should work" );
sf.close();
}
catch (HibernateException he) {
//success
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
}

View File

@ -33,6 +33,7 @@ import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.hibernate.testing.junit.functional.annotations.HibernateTestCase;
/**
@ -103,7 +104,7 @@ public abstract class TestCase extends HibernateTestCase {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile );
getCfg().addInputStream( is );
}
sessions = getCfg().buildSessionFactory();
sessions = getCfg().buildSessionFactory( getServiceRegistry() );
}
catch ( Exception e ) {
e.printStackTrace();
@ -146,5 +147,6 @@ public abstract class TestCase extends HibernateTestCase {
}
catch ( Exception ignore ) {
}
super.closeResources();
}
}

View File

@ -29,9 +29,11 @@ import junit.framework.TestCase;
import org.hibernate.EntityMode;
import org.hibernate.MappingException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.property.BasicPropertyAccessor;
import org.hibernate.property.DirectPropertyAccessor;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.PojoEntityTuplizer;
@ -43,12 +45,24 @@ import org.hibernate.tuple.entity.PojoEntityTuplizer;
*/
public class AccessMappingTest extends TestCase {
private ServiceRegistryHolder serviceRegistryHolder;
protected void setUp() {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
protected void tearDown() {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
public void testInconsistentAnnotationPlacement() throws Exception {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass( Course1.class );
cfg.addAnnotatedClass( Student.class );
try {
cfg.buildSessionFactory();
cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail( "@Id and @OneToMany are not placed consistently in test entities. SessionFactory creation should fail." );
}
catch ( MappingException e ) {
@ -61,7 +75,7 @@ public class AccessMappingTest extends TestCase {
Class<?> classUnderTest = Course6.class;
cfg.addAnnotatedClass( classUnderTest );
cfg.addAnnotatedClass( Student.class );
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory();
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() )
.getEntityMetamodel();
PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO );
@ -76,7 +90,7 @@ public class AccessMappingTest extends TestCase {
Class<?> classUnderTest = Course7.class;
cfg.addAnnotatedClass( classUnderTest );
cfg.addAnnotatedClass( Student.class );
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory();
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() )
.getEntityMetamodel();
PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO );
@ -91,7 +105,7 @@ public class AccessMappingTest extends TestCase {
Class<?> classUnderTest = Course2.class;
cfg.addAnnotatedClass( classUnderTest );
cfg.addAnnotatedClass( Student.class );
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory();
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() )
.getEntityMetamodel();
PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO );
@ -106,7 +120,7 @@ public class AccessMappingTest extends TestCase {
cfg.addAnnotatedClass( Course4.class );
cfg.addAnnotatedClass( Student.class );
try {
cfg.buildSessionFactory();
cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail( "@Id and @OneToMany are not placed consistently in test entities. SessionFactory creation should fail." );
}
catch ( MappingException e ) {
@ -119,7 +133,7 @@ public class AccessMappingTest extends TestCase {
Class<?> classUnderTest = Course3.class;
cfg.addAnnotatedClass( classUnderTest );
cfg.addAnnotatedClass( Student.class );
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory();
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() )
.getEntityMetamodel();
PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO );
@ -139,7 +153,7 @@ public class AccessMappingTest extends TestCase {
Class<?> classUnderTest = Course5.class;
cfg.addAnnotatedClass( classUnderTest );
cfg.addAnnotatedClass( Student.class );
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory();
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() )
.getEntityMetamodel();
PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO );
@ -160,7 +174,7 @@ public class AccessMappingTest extends TestCase {
cfg.addAnnotatedClass( classUnderTest );
cfg.addAnnotatedClass( Person.class );
cfg.addAnnotatedClass( Being.class );
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory();
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
EntityMetamodel metaModel = factory.getEntityPersister( classUnderTest.getName() )
.getEntityMetamodel();
PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO );
@ -175,7 +189,7 @@ public class AccessMappingTest extends TestCase {
cfg.addAnnotatedClass( Horse.class );
cfg.addAnnotatedClass( Animal.class );
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory();
SessionFactoryImplementor factory = ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
EntityMetamodel metaModel = factory.getEntityPersister( Animal.class.getName() )
.getEntityMetamodel();
PojoEntityTuplizer tuplizer = ( PojoEntityTuplizer ) metaModel.getTuplizer( EntityMode.POJO );
@ -200,6 +214,6 @@ public class AccessMappingTest extends TestCase {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass( Course8.class );
cfg.addAnnotatedClass( Student.class );
cfg.buildSessionFactory();
cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
}

View File

@ -34,9 +34,11 @@ import junit.framework.TestCase;
import org.hibernate.EntityMode;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.property.BasicPropertyAccessor;
import org.hibernate.property.DirectPropertyAccessor;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.PojoEntityTuplizer;
@ -48,6 +50,18 @@ import org.hibernate.tuple.entity.PojoEntityTuplizer;
*/
public class XmlAccessTest extends TestCase {
private ServiceRegistryHolder serviceRegistryHolder;
protected void setUp() {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
protected void tearDown() {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
public void testAccessOnBasicXmlElement() throws Exception {
Class<?> classUnderTest = Tourist.class;
List<Class<?>> classes = new ArrayList<Class<?>>();
@ -170,7 +184,7 @@ public class XmlAccessTest extends TestCase {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( configFile );
cfg.addInputStream( is );
}
return ( SessionFactoryImplementor ) cfg.buildSessionFactory();
return ( SessionFactoryImplementor ) cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
// uses the first getter of the tupelizer for the assertions

View File

@ -8,6 +8,9 @@ import junit.framework.TestCase;
import org.hibernate.MappingException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -21,12 +24,24 @@ public class BackquoteTest extends TestCase {
private Logger log = LoggerFactory.getLogger(BackquoteTest.class);
private ServiceRegistryHolder serviceRegistryHolder;
protected void setUp() {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
protected void tearDown() {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
public void testBackquotes() {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Bug.class);
config.addAnnotatedClass(Category.class);
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
catch( Exception e ) {
StringWriter writer = new StringWriter();
@ -48,7 +63,7 @@ public class BackquoteTest extends TestCase {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Printer.class);
config.addAnnotatedClass(PrinterCable.class);
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail("expected MappingException to be thrown");
}
//we WANT MappingException to be thrown

View File

@ -5,6 +5,7 @@ import junit.framework.TestCase;
import org.hibernate.AnnotationException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* @author Emmanuel Bernard
@ -13,16 +14,23 @@ public class DuplicateTest extends TestCase {
public void testDuplicateEntityName() throws Exception {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
ServiceRegistryHolder serviceRegistryHolder = null;
try {
cfg.addAnnotatedClass( Flight.class );
cfg.addAnnotatedClass( org.hibernate.test.annotations.Flight.class );
cfg.addResource( "org/hibernate/test/annotations/orm.xml" );
cfg.addResource( "org/hibernate/test/annotations/duplicatedgenerator/orm.xml" );
cfg.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() );
cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail( "Should not be able to map the same entity name twice" );
}
catch (AnnotationException ae) {
//success
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
}

View File

@ -637,7 +637,7 @@ public class BasicHibernateAnnotationsTest extends TestCase {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(LocalContactDetails.class);
config.buildSessionFactory();
config.buildSessionFactory( getServiceRegistry() );
fail("Did not throw expected exception");
}
catch( AnnotationException ex ) {

View File

@ -33,7 +33,9 @@ import org.slf4j.LoggerFactory;
import org.hibernate.MappingException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* Test case for HHH-4812
@ -44,13 +46,27 @@ public class FetchProfileTest extends TestCase {
private Logger log = LoggerFactory.getLogger( FetchProfileTest.class );
private ServiceRegistryHolder serviceRegistryHolder;
protected void setUp() {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
protected void tearDown() {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
public void testFetchProfileConfigured() {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass( Customer.class );
config.addAnnotatedClass( Order.class );
config.addAnnotatedClass( SupportTickets.class );
config.addAnnotatedClass( Country.class );
SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory();
SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory(
serviceRegistryHolder.getServiceRegistry()
);
assertTrue(
"fetch profile not parsed properly",
@ -69,7 +85,7 @@ public class FetchProfileTest extends TestCase {
config.addAnnotatedClass( Country.class );
try {
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail();
}
catch ( MappingException e ) {
@ -84,7 +100,7 @@ public class FetchProfileTest extends TestCase {
config.addAnnotatedClass( Country.class );
try {
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail();
}
catch ( MappingException e ) {
@ -99,7 +115,7 @@ public class FetchProfileTest extends TestCase {
config.addAnnotatedClass( Country.class );
try {
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail();
}
catch ( MappingException e ) {
@ -116,7 +132,9 @@ public class FetchProfileTest extends TestCase {
.getContextClassLoader()
.getResourceAsStream( "org/hibernate/test/annotations/fetchprofile/mappings.hbm.xml" );
config.addInputStream( is );
SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory();
SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory(
serviceRegistryHolder.getServiceRegistry()
);
assertTrue(
"fetch profile not parsed properly",
@ -129,7 +147,7 @@ public class FetchProfileTest extends TestCase {
config.addAnnotatedClass( Order.class );
config.addAnnotatedClass( Country.class );
try {
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail();
}
catch ( MappingException e ) {
@ -144,7 +162,9 @@ public class FetchProfileTest extends TestCase {
config.addAnnotatedClass( SupportTickets.class );
config.addAnnotatedClass( Country.class );
config.addPackage( Customer.class.getPackage().getName() );
SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory();
SessionFactoryImplementor sessionImpl = ( SessionFactoryImplementor ) config.buildSessionFactory(
serviceRegistryHolder.getServiceRegistry()
);
assertTrue(
"fetch profile not parsed properly",

View File

@ -7,8 +7,11 @@ import java.io.StringWriter;
import junit.framework.TestCase;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -21,6 +24,18 @@ public class FkCircularityTest extends TestCase {
private Logger log = LoggerFactory.getLogger(FkCircularityTest.class);
private ServiceRegistryHolder serviceRegistryHolder;
protected void setUp() {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
protected void tearDown() {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
public void testJoinedSublcassesInPK() {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
@ -28,7 +43,7 @@ public class FkCircularityTest extends TestCase {
config.addAnnotatedClass(B.class);
config.addAnnotatedClass(C.class);
config.addAnnotatedClass(D.class);
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
String[] schema = config
.generateSchemaCreationScript(new SQLServerDialect());
for (String s : schema) {
@ -50,7 +65,7 @@ public class FkCircularityTest extends TestCase {
config.addAnnotatedClass(ClassB.class);
config.addAnnotatedClass(ClassC.class);
config.addAnnotatedClass(ClassD.class);
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
String[] schema = config
.generateSchemaCreationScript(new HSQLDialect());
for (String s : schema) {

View File

@ -34,7 +34,7 @@ public class JoinColumnOverrideTest extends TestCase {
config.addAnnotatedClass(Bunny.class);
config.addAnnotatedClass(PointyTooth.class);
config.addAnnotatedClass(TwinkleToes.class);
config.buildSessionFactory();
config.buildSessionFactory( getServiceRegistry() );
String[] schema = config
.generateSchemaCreationScript(new SQLServerDialect());
for (String s : schema) {

View File

@ -34,7 +34,7 @@ public class JoinColumnOverrideTest extends TestCase {
config.addAnnotatedClass(Bunny.class);
config.addAnnotatedClass(PointyTooth.class);
config.addAnnotatedClass(TwinkleToes.class);
config.buildSessionFactory();
config.buildSessionFactory( getServiceRegistry() );
String[] schema = config
.generateSchemaCreationScript(new SQLServerDialect());
for (String s : schema) {

View File

@ -143,7 +143,7 @@ public class ImmutableTest extends TestCase {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Foobar.class);
config.buildSessionFactory();
config.buildSessionFactory( getServiceRegistry() );
fail();
} catch (AnnotationException ae) {
log.debug("succes");

View File

@ -9,8 +9,11 @@ import junit.framework.TestCase;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.EJB3NamingStrategy;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.Mappings;
import org.hibernate.mapping.Table;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -23,13 +26,25 @@ public class NamingStrategyTest extends TestCase {
private Logger log = LoggerFactory.getLogger(NamingStrategyTest.class);
private ServiceRegistryHolder serviceRegistryHolder;
protected void setUp() {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
protected void tearDown() {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
public void testWithCustomNamingStrategy() throws Exception {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.setNamingStrategy(new DummyNamingStrategy());
config.addAnnotatedClass(Address.class);
config.addAnnotatedClass(Person.class);
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
catch( Exception e ) {
StringWriter writer = new StringWriter();
@ -45,7 +60,7 @@ public class NamingStrategyTest extends TestCase {
config.setNamingStrategy(EJB3NamingStrategy.INSTANCE);
config.addAnnotatedClass(A.class);
config.addAnnotatedClass(AddressEntry.class);
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
Mappings mappings = config.createMappings();
boolean foundIt = false;
@ -73,7 +88,7 @@ public class NamingStrategyTest extends TestCase {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Address.class);
config.addAnnotatedClass(Person.class);
config.buildSessionFactory();
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
catch( Exception e ) {
StringWriter writer = new StringWriter();

View File

@ -5,6 +5,7 @@ import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.SessionFactory;
import org.hibernate.AnnotationException;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* @author Emmanuel Bernard
@ -15,12 +16,19 @@ public class OneToOneErrorTest extends junit.framework.TestCase {
cfg.addAnnotatedClass( Show.class )
.addAnnotatedClass( ShowDescription.class );
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
ServiceRegistryHolder serviceRegistryHolder = null;
try {
SessionFactory sf = cfg.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
SessionFactory sf = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
fail( "Wrong mappedBy does not fail property" );
}
catch (AnnotationException e) {
//success
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
}

View File

@ -4,7 +4,10 @@ package org.hibernate.test.annotations.onetoone.primarykey;
import junit.framework.TestCase;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -19,11 +22,14 @@ public class NullablePrimaryKeyTest extends TestCase {
private Logger log = LoggerFactory.getLogger(NullablePrimaryKeyTest.class);
public void testGeneratedSql() {
ServiceRegistryHolder serviceRegistryHolder = null;
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Address.class);
config.addAnnotatedClass(Person.class);
config.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
String[] schema = config
.generateSchemaCreationScript(new SQLServerDialect());
for (String s : schema) {
@ -35,5 +41,10 @@ public class NullablePrimaryKeyTest extends TestCase {
} catch (Exception e) {
fail(e.getMessage());
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
}

View File

@ -27,6 +27,7 @@ import javax.persistence.Id;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.hibernate.testing.junit.UnitTestCase;
import org.hibernate.cfg.Configuration;
import org.hibernate.util.SerializationHelper;
@ -103,9 +104,21 @@ public class ConfigurationSerializationTest extends UnitTestCase {
byte[] bytes = SerializationHelper.serialize( cfg );
cfg = ( Configuration ) SerializationHelper.deserialize( bytes );
// try to build SF
SessionFactory factory = cfg.buildSessionFactory();
factory.close();
SessionFactory factory = null;
ServiceRegistryHolder serviceRegistryHolder = null;
try {
serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() );
// try to build SF
factory = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry());
}
finally {
if ( factory != null ) {
factory.close();
}
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
@Entity

View File

@ -0,0 +1,81 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.test.common;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.internal.ServicesRegistryBootstrap;
import org.hibernate.engine.jdbc.internal.JdbcServicesImpl;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.internal.ServicesRegistryImpl;
import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator;
import org.hibernate.service.spi.ServicesRegistry;
/**
* @author Gail Badner
*/
public class ServiceRegistryHolder {
private final ServicesRegistryImpl serviceRegistry;
private final Properties properties;
public ServiceRegistryHolder(Map props) {
properties = new Properties();
properties.putAll( props );
Environment.verifyProperties( properties );
ConfigurationHelper.resolvePlaceHolders( properties );
serviceRegistry = new ServicesRegistryBootstrap().initiateServicesRegistry( properties );
properties.putAll( serviceRegistry.getService( JdbcServices.class ).getDialect().getDefaultProperties() );
}
public Properties getProperties() {
return properties;
}
public ServicesRegistry getServiceRegistry() {
return serviceRegistry;
}
public JdbcServices getJdbcServices() {
return serviceRegistry.getService( JdbcServices.class );
}
public JdbcServicesImpl getJdbcServicesImpl() {
return ( JdbcServicesImpl ) getJdbcServices();
}
public ClassLoaderService getClassLoaderService() {
return serviceRegistry.getService( ClassLoaderService.class );
}
public void destroy() {
if ( serviceRegistry != null ) {
serviceRegistry.destroy();
}
}
}

View File

@ -10,9 +10,10 @@ import org.hibernate.ConnectionReleaseMode;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.ConnectionProviderFactory;
import org.hibernate.connection.UserSuppliedConnectionProvider;
import org.hibernate.service.jdbc.connections.internal.UserSuppliedConnectionProviderImpl;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.test.common.ConnectionProviderBuilder;
import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite;
import org.hibernate.tool.hbm2ddl.SchemaExport;
@ -23,7 +24,7 @@ import org.hibernate.tool.hbm2ddl.SchemaExport;
*/
public class SuppliedConnectionTest extends ConnectionManagementTestCase {
private ConnectionProvider cp = ConnectionProviderFactory.newConnectionProvider();
private ConnectionProvider cp = ConnectionProviderBuilder.buildConnectionProvider();
private Connection connectionUnderTest;
public SuppliedConnectionTest(String name) {
@ -50,7 +51,7 @@ public class SuppliedConnectionTest extends ConnectionManagementTestCase {
public void configure(Configuration cfg) {
super.configure( cfg );
cfg.setProperty( Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString() );
cfg.setProperty( Environment.CONNECTION_PROVIDER, UserSuppliedConnectionProvider.class.getName() );
cfg.setProperty( Environment.CONNECTION_PROVIDER, UserSuppliedConnectionProviderImpl.class.getName() );
boolean supportsScroll = true;
Connection conn = null;
try {
@ -112,7 +113,10 @@ public class SuppliedConnectionTest extends ConnectionManagementTestCase {
}
}
try {
cp.close();
if ( cp instanceof Stoppable ) {
( ( Stoppable ) cp ).stop();
}
cp = null;
}
catch( Throwable ignore ) {
}

View File

@ -47,7 +47,7 @@ public class ExtendsTest extends UnitTestCase {
cfg.addResource( getBaseForMappings() + "extendshbm/Person.hbm.xml" );
cfg.addResource( getBaseForMappings() + "extendshbm/Employee.hbm.xml" );
cfg.buildSessionFactory();
cfg.buildSessionFactory( getServiceRegistry() );
assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) );
assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Person" ) );
@ -103,7 +103,7 @@ public class ExtendsTest extends UnitTestCase {
);
cfg.addResource( getBaseForMappings() + "extendshbm/Employee.hbm.xml" );
cfg.buildSessionFactory();
cfg.buildSessionFactory( getServiceRegistry() );
fail( "Should not be able to build sessionfactory without a Person" );
}
@ -119,7 +119,7 @@ public class ExtendsTest extends UnitTestCase {
try {
cfg.addResource( getBaseForMappings() + "extendshbm/allseparateinone.hbm.xml" );
cfg.buildSessionFactory();
cfg.buildSessionFactory( getServiceRegistry() );
assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) );
assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Person" ) );

View File

@ -3,12 +3,14 @@ package org.hibernate.test.instrument.cases;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* @author Steve Ebersole
*/
public abstract class AbstractExecutable implements Executable {
private ServiceRegistryHolder serviceRegistryHolder;
private SessionFactory factory;
public final void prepare() {
@ -17,7 +19,8 @@ public abstract class AbstractExecutable implements Executable {
for ( int i = 0; i < resources.length; i++ ) {
cfg.addResource( resources[i] );
}
factory = cfg.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( cfg.getProperties() );
factory = cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
public final void complete() {
@ -26,6 +29,9 @@ public abstract class AbstractExecutable implements Executable {
}
finally {
factory.close();
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}

View File

@ -34,10 +34,8 @@ import org.hibernate.Query;
import org.hibernate.QueryException;
import org.hibernate.ScrollableResults;
import org.hibernate.Transaction;
import org.hibernate.cfg.Environment;
import org.hibernate.classic.Session;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.DriverManagerConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
@ -57,6 +55,7 @@ import org.hibernate.dialect.SybaseASE15Dialect;
import org.hibernate.dialect.SybaseDialect;
import org.hibernate.dialect.TimesTenDialect;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.test.common.ConnectionProviderBuilder;
import org.hibernate.testing.junit.functional.FunctionalTestClassTestSuite;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.util.JoinedIterator;
@ -4346,8 +4345,7 @@ public class FooBarTest extends LegacyTestCase {
}
public void testUserProvidedConnection() throws Exception {
ConnectionProvider dcp = new DriverManagerConnectionProvider();
dcp.configure( Environment.getProperties() );
ConnectionProvider dcp = ConnectionProviderBuilder.buildConnectionProvider();
Session s = getSessions().openSession( dcp.getConnection() );
Transaction tx = s.beginTransaction();
s.createQuery( "from Fo" ).list();

View File

@ -29,7 +29,7 @@ public class MigrationTest extends UnitTestCase {
v1cfg.addResource( resource1 );
new SchemaExport( v1cfg ).execute( false, true, true, false );
SchemaUpdate v1schemaUpdate = new SchemaUpdate( v1cfg );
SchemaUpdate v1schemaUpdate = new SchemaUpdate( getJdbcServices(), v1cfg );
v1schemaUpdate.execute( true, true );
assertEquals( 0, v1schemaUpdate.getExceptions().size() );
@ -37,11 +37,11 @@ public class MigrationTest extends UnitTestCase {
Configuration v2cfg = new Configuration();
v2cfg.addResource( resource2 );
SchemaUpdate v2schemaUpdate = new SchemaUpdate( v2cfg );
SchemaUpdate v2schemaUpdate = new SchemaUpdate( getJdbcServices(), v2cfg );
v2schemaUpdate.execute( true, true );
assertEquals( 0, v2schemaUpdate.getExceptions().size() );
new SchemaExport( v2cfg ).drop( false, true );
new SchemaExport( getJdbcServices(), v2cfg ).drop( false, true );
}

View File

@ -86,7 +86,7 @@ public class StatsTest extends FunctionalTestCase {
Collection coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
coll.setFetchMode(FetchMode.JOIN);
coll.setLazy(false);
SessionFactory sf = getCfg().buildSessionFactory();
SessionFactory sf = getCfg().buildSessionFactory( getServiceRegistry() );
stats = sf.getStatistics();
stats.clear();
stats.setStatisticsEnabled(true);
@ -108,7 +108,7 @@ public class StatsTest extends FunctionalTestCase {
coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
coll.setFetchMode(FetchMode.SELECT);
coll.setLazy(false);
sf = getCfg().buildSessionFactory();
sf = getCfg().buildSessionFactory( getServiceRegistry() );
stats = sf.getStatistics();
stats.clear();
stats.setStatisticsEnabled(true);

View File

@ -35,6 +35,11 @@ import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.ServicesRegistry;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* A basic JUnit {@link junit.framework.TestCase} subclass for
@ -46,6 +51,8 @@ public abstract class UnitTestCase extends junit.framework.TestCase {
private static final Logger log = LoggerFactory.getLogger( UnitTestCase.class );
private ServiceRegistryHolder serviceRegistryHolder;
public UnitTestCase(String string) {
super( string );
}
@ -81,6 +88,29 @@ public abstract class UnitTestCase extends junit.framework.TestCase {
}
}
@Override
protected void tearDown() throws Exception {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
serviceRegistryHolder = null;
}
}
protected ServicesRegistry getServiceRegistry() {
if ( serviceRegistryHolder == null ) {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
return serviceRegistryHolder.getServiceRegistry();
}
protected JdbcServices getJdbcServices() {
return getServiceRegistry().getService( JdbcServices.class );
}
protected ConnectionProvider getConnectionProvider() {
return getJdbcServices().getConnectionProvider();
}
private static class FailureExpectedTestPassedException extends Exception {
public FailureExpectedTestPassedException() {
super( "Test marked as FailureExpected, but did not fail!" );

View File

@ -23,9 +23,11 @@
*/
package org.hibernate.testing.junit.functional;
import java.util.HashMap;
import java.util.Iterator;
import java.sql.Blob;
import java.sql.Clob;
import java.util.Map;
import org.hibernate.dialect.Dialect;
import org.hibernate.cfg.Configuration;
@ -37,6 +39,9 @@ import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Collection;
import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator;
import org.hibernate.service.spi.ServicesRegistry;
import org.hibernate.test.common.ServiceRegistryHolder;
/**
* {@inheritDoc}
@ -49,6 +54,8 @@ public class ExecutionEnvironment {
private final ExecutionEnvironment.Settings settings;
private Map conectionProviderInjectionProperties;
private ServiceRegistryHolder serviceRegistryHolder;
private Configuration configuration;
private SessionFactory sessionFactory;
private boolean allowRebuild;
@ -73,11 +80,15 @@ public class ExecutionEnvironment {
return configuration;
}
public ServicesRegistry getServiceRegistry() {
return serviceRegistryHolder.getServiceRegistry();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void initialize() {
public void initialize(Map conectionProviderInjectionProperties) {
if ( sessionFactory != null ) {
throw new IllegalStateException( "attempt to initialize already initialized ExecutionEnvironment" );
}
@ -85,6 +96,7 @@ public class ExecutionEnvironment {
return;
}
this.conectionProviderInjectionProperties = conectionProviderInjectionProperties;
Configuration configuration = new Configuration();
configuration.setProperty( Environment.CACHE_PROVIDER, "org.hibernate.cache.HashtableCacheProvider" );
@ -103,13 +115,28 @@ public class ExecutionEnvironment {
applyCacheSettings( configuration );
settings.afterConfigurationBuilt( configuration.createMappings(), getDialect() );
SessionFactory sessionFactory = configuration.buildSessionFactory();
this.configuration = configuration;
this.sessionFactory = sessionFactory;
serviceRegistryHolder = new ServiceRegistryHolder( getServiceRegistryProperties() );
sessionFactory = configuration.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
settings.afterSessionFactoryBuilt( ( SessionFactoryImplementor ) sessionFactory );
}
private Map getServiceRegistryProperties() {
Map serviceRegistryProperties = configuration.getProperties();
if ( conectionProviderInjectionProperties != null && conectionProviderInjectionProperties.size() > 0 ) {
serviceRegistryProperties = new HashMap(
configuration.getProperties().size() + conectionProviderInjectionProperties.size()
);
serviceRegistryProperties.putAll( configuration.getProperties() );
serviceRegistryProperties.put(
ConnectionProviderInitiator.INJECTION_DATA, conectionProviderInjectionProperties
);
}
return serviceRegistryProperties;
}
private void applyMappings(Configuration configuration) {
String[] mappings = settings.getMappings();
for ( String mapping : mappings ) {
@ -159,7 +186,12 @@ public class ExecutionEnvironment {
sessionFactory.close();
sessionFactory = null;
}
sessionFactory = configuration.buildSessionFactory();
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
serviceRegistryHolder = null;
}
serviceRegistryHolder = new ServiceRegistryHolder( getServiceRegistryProperties() );
sessionFactory = configuration.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
settings.afterSessionFactoryBuilt( ( SessionFactoryImplementor ) sessionFactory );
}
@ -168,6 +200,10 @@ public class ExecutionEnvironment {
sessionFactory.close();
sessionFactory = null;
}
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
serviceRegistryHolder = null;
}
configuration = null;
}

View File

@ -23,6 +23,7 @@
*/
package org.hibernate.testing.junit.functional;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
@ -90,11 +91,15 @@ public abstract class FunctionalTestCase extends UnitTestCase implements Executi
log.info( "Building locally managed execution env" );
isEnvironmentLocallyManaged = true;
environment = new ExecutionEnvironment( this );
environment.initialize();
environment.initialize( getConnectionProviderInjectionProperties() );
}
prepareTest();
}
protected Map getConnectionProviderInjectionProperties() {
return Collections.EMPTY_MAP;
}
/**
* Override {@link junit.framework.TestCase#tearDown()} to tear down
* the execution environment if it is locally managed.

View File

@ -23,6 +23,9 @@
*/
package org.hibernate.testing.junit.functional;
import java.util.Collections;
import java.util.Map;
import junit.framework.TestSuite;
import junit.framework.Test;
import junit.framework.TestResult;
@ -127,13 +130,17 @@ public class FunctionalTestClassTestSuite extends TestSuite {
log.info( "Building aggregated execution environment" );
try {
environment = new ExecutionEnvironment( settings );
environment.initialize();
environment.initialize( getConnectionProviderInjectionProperties() );
}
catch( Throwable t ) {
environmentSetupError = t;
}
}
protected Map getConnectionProviderInjectionProperties() {
return Collections.EMPTY_MAP;
}
protected void tearDown() {
if ( environment != null ) {
log.info( "Destroying aggregated execution environment" );

View File

@ -38,8 +38,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.jdbc.Work;
import org.hibernate.service.spi.ServicesRegistry;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.hibernate.testing.junit.DialectChecks;
import org.hibernate.testing.junit.FailureExpected;
import org.hibernate.testing.junit.RequiresDialect;
@ -61,6 +65,7 @@ public abstract class HibernateTestCase extends TestCase {
protected static Configuration cfg;
private static Class<?> lastTestClass;
private ServiceRegistryHolder serviceRegistryHolder;
public HibernateTestCase() {
super();
@ -147,6 +152,17 @@ public abstract class HibernateTestCase extends TestCase {
handleUnclosedResources();
}
protected ServicesRegistry getServiceRegistry() {
if ( serviceRegistryHolder == null ) {
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
}
return serviceRegistryHolder.getServiceRegistry();
}
protected JdbcServices getJdbcServices() {
return getServiceRegistry().getService( JdbcServices.class );
}
protected static class Skip {
private final String reason;
private final String testDescription;
@ -265,7 +281,12 @@ public abstract class HibernateTestCase extends TestCase {
protected abstract void handleUnclosedResources();
protected abstract void closeResources();
protected void closeResources() {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
serviceRegistryHolder = null;
}
}
protected String[] getAnnotatedPackages() {
return new String[] { };
@ -295,12 +316,12 @@ public abstract class HibernateTestCase extends TestCase {
}
protected void runSchemaGeneration() {
SchemaExport export = new SchemaExport( cfg );
SchemaExport export = new SchemaExport( getJdbcServices(), cfg );
export.create( true, true );
}
protected void runSchemaDrop() {
SchemaExport export = new SchemaExport( cfg );
SchemaExport export = new SchemaExport( getJdbcServices(), cfg );
export.drop( true, true );
}

View File

@ -28,8 +28,9 @@ import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.ConnectionProviderFactory;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.test.common.ConnectionProviderBuilder;
/**
* A {@link ConnectionProvider} implementation adding JTA-style transactionality
@ -39,7 +40,7 @@ import org.hibernate.connection.ConnectionProviderFactory;
* @author Steve Ebersole
*/
public class ConnectionProviderImpl implements ConnectionProvider {
private static ConnectionProvider actualConnectionProvider = ConnectionProviderFactory.newConnectionProvider();
private static ConnectionProvider actualConnectionProvider = ConnectionProviderBuilder.buildConnectionProvider();
private boolean isTransactional;
@ -74,7 +75,9 @@ public class ConnectionProviderImpl implements ConnectionProvider {
}
public void close() throws HibernateException {
actualConnectionProvider.close();
if ( actualConnectionProvider instanceof Stoppable ) {
( ( Stoppable ) actualConnectionProvider ).stop();
}
}
public boolean supportsAggressiveRelease() {

View File

@ -74,7 +74,6 @@ import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.Settings;
import org.hibernate.cfg.SettingsFactory;
import org.hibernate.cfg.annotations.reflection.XMLContext;
import org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider;
import org.hibernate.ejb.instrument.InterceptFieldClassFileTransformer;
@ -94,6 +93,9 @@ import org.hibernate.mapping.AuxiliaryDatabaseObject;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.secure.JACCConfiguration;
import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.ServicesRegistry;
import org.hibernate.transaction.JDBCTransactionFactory;
import org.hibernate.util.CollectionHelper;
import org.hibernate.util.ReflectHelper;
@ -142,7 +144,7 @@ public class Ejb3Configuration implements Serializable, Referenceable {
private String cfgXmlResource;
private AnnotationConfiguration cfg;
private SettingsFactory settingsFactory;
private final Map connectionProviderInjectionData;
//made transient and not restored in deserialization on purpose, should no longer be called after restoration
private transient EventListenerConfigurator listenerConfigurator;
private PersistenceUnitTransactionType transactionType;
@ -153,8 +155,8 @@ public class Ejb3Configuration implements Serializable, Referenceable {
public Ejb3Configuration() {
settingsFactory = new InjectionSettingsFactory();
cfg = new AnnotationConfiguration( settingsFactory );
connectionProviderInjectionData = new HashMap();
cfg = new AnnotationConfiguration();
cfg.setEntityNotFoundDelegate( ejb3EntityNotFoundDelegate );
listenerConfigurator = new EventListenerConfigurator( this );
}
@ -169,7 +171,7 @@ public class Ejb3Configuration implements Serializable, Referenceable {
if ( ds != null ) {
Map cpInjection = new HashMap();
cpInjection.put( "dataSource", ds );
( (InjectionSettingsFactory) settingsFactory ).setConnectionProviderInjectionData( cpInjection );
connectionProviderInjectionData.put( ConnectionProviderInitiator.INJECTION_DATA, cpInjection );
this.setProperty( Environment.CONNECTION_PROVIDER, InjectedDataSourceConnectionProvider.class.getName() );
}
}
@ -900,11 +902,11 @@ public class Ejb3Configuration implements Serializable, Referenceable {
configure( (Properties)null, null );
NamingHelper.bind(this);
return new EntityManagerFactoryImpl(
cfg.buildSessionFactory(),
transactionType,
discardOnClose,
getSessionInterceptorClass( cfg.getProperties() ),
cfg
cfg,
connectionProviderInjectionData
);
}
catch (HibernateException e) {
@ -1350,8 +1352,9 @@ public class Ejb3Configuration implements Serializable, Referenceable {
}
}
public Settings buildSettings() throws HibernateException {
/*
TODO: not needed any more?
public Settings buildSettings(ConnectionProvider connectionProvider) throws HibernateException {
Thread thread = null;
ClassLoader contextClassLoader = null;
if (overridenClassLoader != null) {
@ -1360,12 +1363,13 @@ public class Ejb3Configuration implements Serializable, Referenceable {
thread.setContextClassLoader( overridenClassLoader );
}
try {
return settingsFactory.buildSettings( cfg.getProperties() );
return settingsFactory.buildSettings( cfg.getProperties(), connectionProvider );
}
finally {
if (thread != null) thread.setContextClassLoader( contextClassLoader );
}
}
*/
public Ejb3Configuration addProperties(Properties props) {
cfg.addProperties( props );
@ -1501,8 +1505,8 @@ public class Ejb3Configuration implements Serializable, Referenceable {
return cfg.getEventListeners();
}
SessionFactory buildSessionFactory() throws HibernateException {
return cfg.buildSessionFactory();
SessionFactory buildSessionFactory(ServicesRegistry serviceRegistry) throws HibernateException {
return cfg.buildSessionFactory( serviceRegistry );
}
public Iterator getTableMappings() {

View File

@ -41,6 +41,7 @@ import org.hibernate.SessionFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.EntityMode;
import org.hibernate.cfg.internal.ServicesRegistryBootstrap;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.mapping.PersistentClass;
@ -48,6 +49,8 @@ import org.hibernate.cfg.Configuration;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.metamodel.MetamodelImpl;
import org.hibernate.ejb.util.PersistenceUtilHelper;
import org.hibernate.service.internal.ServicesRegistryImpl;
import org.hibernate.service.spi.ServicesRegistry;
/**
* Actual Hiberate implementation of {@link javax.persistence.EntityManagerFactory}.
@ -57,6 +60,7 @@ import org.hibernate.ejb.util.PersistenceUtilHelper;
* @author Steve Ebersole
*/
public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory {
private final transient ServicesRegistryImpl serviceRegistry;
private final SessionFactory sessionFactory;
private final PersistenceUnitTransactionType transactionType;
private final boolean discardOnClose;
@ -65,16 +69,25 @@ public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory {
private final Metamodel metamodel;
private final HibernatePersistenceUnitUtil util;
private final Map<String,Object> properties;
private final Map connectionProviderInjectionData;
private final PersistenceUtilHelper.MetadataCache cache = new PersistenceUtilHelper.MetadataCache();
@SuppressWarnings( "unchecked" )
public EntityManagerFactoryImpl(
SessionFactory sessionFactory,
PersistenceUnitTransactionType transactionType,
boolean discardOnClose,
Class<?> sessionInterceptorClass,
Configuration cfg) {
this.sessionFactory = sessionFactory;
Configuration cfg,
Map connectionProviderInjectionData) {
// FIXME: Get rid of this temporary way of creating the service registry for EM
Map serviceRegistryProperties = new HashMap(
cfg.getProperties().size() + connectionProviderInjectionData.size()
);
serviceRegistryProperties.putAll( cfg.getProperties() );
serviceRegistryProperties.putAll( connectionProviderInjectionData );
this.serviceRegistry = new ServicesRegistryBootstrap().initiateServicesRegistry( serviceRegistryProperties );
this.sessionFactory = cfg.buildSessionFactory( serviceRegistry );
this.transactionType = transactionType;
this.discardOnClose = discardOnClose;
this.sessionInterceptorClass = sessionInterceptorClass;
@ -93,6 +106,7 @@ public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory {
addAll( props, ( (SessionFactoryImplementor) sessionFactory ).getProperties() );
addAll( props, cfg.getProperties() );
this.properties = Collections.unmodifiableMap( props );
this.connectionProviderInjectionData = new HashMap();
}
private static void addAll(HashMap<String, Object> propertyMap, Properties properties) {
@ -125,6 +139,7 @@ public class EntityManagerFactoryImpl implements HibernateEntityManagerFactory {
public void close() {
sessionFactory.close();
serviceRegistry.destroy();
}
public Map<String, Object> getProperties() {

View File

@ -24,12 +24,14 @@
package org.hibernate.ejb;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.LoadState;
import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.ProviderUtil;
import org.hibernate.cfg.internal.ServicesRegistryBootstrap;
import org.hibernate.ejb.util.PersistenceUtilHelper;
/**

View File

@ -1,53 +0,0 @@
/*
* Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
//$Id$
package org.hibernate.ejb;
import java.util.Map;
import java.util.Properties;
import org.hibernate.cfg.SettingsFactory;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.ConnectionProviderFactory;
/**
* @author Emmanuel Bernard
*/
public class InjectionSettingsFactory extends SettingsFactory {
private Map connectionProviderInjectionData;
/**
* Map<String,Object> where the key represents the javabean property in witch
* Object will be injected
*
* @param connectionProviderInjectionData
*
*/
public void setConnectionProviderInjectionData(Map connectionProviderInjectionData) {
this.connectionProviderInjectionData = connectionProviderInjectionData;
}
protected ConnectionProvider createConnectionProvider(Properties properties) {
return ConnectionProviderFactory.newConnectionProvider( properties, connectionProviderInjectionData );
}
}

View File

@ -28,12 +28,13 @@ import javax.sql.DataSource;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.connection.DatasourceConnectionProvider;
import org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* A specialization of {@link DatasourceConnectionProvider} which uses the {@link DataSource} specified vi
* A specialization of {@link DatasourceConnectionProviderImpl} which uses the {@link DataSource} specified vi
* {@link #setDataSource} rather than locating it from JNDI.
* <p/>
* NOTE : {@link #setDataSource} must be called prior to {@link #configure}.
@ -42,7 +43,7 @@ import org.slf4j.Logger;
*
* @author Emmanuel Bernard
*/
public class InjectedDataSourceConnectionProvider extends DatasourceConnectionProvider {
public class InjectedDataSourceConnectionProvider extends DatasourceConnectionProviderImpl {
private final Logger log = LoggerFactory.getLogger( InjectedDataSourceConnectionProvider.class );
private String user;

View File

@ -118,6 +118,7 @@ public abstract class TestCase extends HibernateTestCase {
if ( factory != null ) {
factory.close();
}
super.closeResources();
}
protected EntityManager getOrCreateEntityManager() {

View File

@ -61,7 +61,7 @@ public class MetadataTest extends TestCase {
configure( cfg );
cfg.addAnnotatedClass( WithGenericCollection.class );
cfg.buildMappings();
SessionFactoryImplementor sfi = (SessionFactoryImplementor) cfg.buildSessionFactory();
SessionFactoryImplementor sfi = (SessionFactoryImplementor) cfg.buildSessionFactory( getServiceRegistry() );
MetamodelImpl.buildMetamodel( cfg.getClassMappings(), sfi );
}

View File

@ -9,8 +9,11 @@ import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.testng.annotations.*;
/**
@ -22,6 +25,7 @@ import org.testng.annotations.*;
public abstract class AbstractSessionTest {
protected Configuration config;
private ServiceRegistryHolder serviceRegistryHolder;
private SessionFactory sessionFactory;
private Session session ;
private AuditReader auditReader;
@ -40,7 +44,8 @@ public abstract class AbstractSessionTest {
this.initMappings();
sessionFactory = config.buildSessionFactory();
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
sessionFactory = config.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
protected abstract void initMappings() throws MappingException, URISyntaxException ;
@ -60,7 +65,15 @@ public abstract class AbstractSessionTest {
@AfterClass
public void closeSessionFactory() {
sessionFactory.close();
try {
sessionFactory.close();
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
serviceRegistryHolder = null;
}
}
}

View File

@ -64,7 +64,9 @@ public abstract class AbstractEntityCollectionRegionTestCase extends AbstractReg
Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false);
String entityCfg = "entity";
cfg.setProperty(InfinispanRegionFactory.ENTITY_CACHE_RESOURCE_PROP, entityCfg);
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
supportedAccessTypeTest(regionFactory, cfg.getProperties());
}
@ -82,14 +84,18 @@ public abstract class AbstractEntityCollectionRegionTestCase extends AbstractReg
*/
public void testIsTransactionAware() throws Exception {
Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false);
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
TransactionalDataRegion region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription());
assertTrue("Region is transaction-aware", region.isTransactionAware());
CacheTestUtil.stopRegionFactory(regionFactory, getCacheTestSupport());
cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false);
// Make it non-transactional
cfg.getProperties().remove(Environment.TRANSACTION_MANAGER_STRATEGY);
regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription());
assertFalse("Region is not transaction-aware", region.isTransactionAware());
CacheTestUtil.stopRegionFactory(regionFactory, getCacheTestSupport());
@ -97,7 +103,9 @@ public abstract class AbstractEntityCollectionRegionTestCase extends AbstractReg
public void testGetCacheDataDescription() throws Exception {
Configuration cfg = CacheTestUtil.buildConfiguration("test", InfinispanRegionFactory.class, true, false);
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
TransactionalDataRegion region = (TransactionalDataRegion) createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription());
CacheDataDescription cdd = region.getCacheDataDescription();
assertNotNull(cdd);

View File

@ -72,7 +72,9 @@ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionIm
private void evictOrRemoveTest() throws Exception {
Configuration cfg = createConfiguration();
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
CacheAdapter localCache = getInfinispanCache(regionFactory);
boolean invalidation = localCache.isClusteredInvalidation();
@ -83,7 +85,9 @@ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionIm
getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null);
cfg = createConfiguration();
regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
GeneralDataRegion remoteRegion = (GeneralDataRegion) createRegion(regionFactory,
getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null);
@ -121,7 +125,9 @@ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionIm
private void evictOrRemoveAllTest(String configName) throws Exception {
Configuration cfg = createConfiguration();
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
CacheAdapter localCache = getInfinispanCache(regionFactory);
// Sleep a bit to avoid concurrent FLUSH problem
@ -131,7 +137,9 @@ public abstract class AbstractGeneralDataRegionTestCase extends AbstractRegionIm
getStandardRegionName(REGION_PREFIX), cfg.getProperties(), null);
cfg = createConfiguration();
regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
CacheAdapter remoteCache = getInfinispanCache(regionFactory);
// Sleep a bit to avoid concurrent FLUSH problem

View File

@ -27,6 +27,10 @@ import java.util.Set;
import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.infinispan.util.CacheHelper;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.ServicesRegistry;
import org.hibernate.testing.junit.UnitTestCase;
import org.hibernate.test.cache.infinispan.util.CacheTestSupport;
import org.infinispan.Cache;

View File

@ -53,9 +53,11 @@ import org.hibernate.cache.infinispan.util.CacheAdapter;
import org.hibernate.cache.infinispan.util.CacheAdapterImpl;
import org.hibernate.cache.infinispan.util.FlagAdapter;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase;
import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeJtaTransactionManagerImpl;
import org.hibernate.test.cache.infinispan.util.CacheTestUtil;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.hibernate.util.ComparableComparator;
import org.infinispan.Cache;
import org.infinispan.transaction.tm.BatchModeTransactionManager;
@ -522,6 +524,7 @@ public abstract class AbstractCollectionRegionAccessStrategyTestCase extends Abs
private final String configResource;
private final String configName;
private String preferIPv4Stack;
private ServiceRegistryHolder serviceRegistryHolder;
public AccessStrategyTestSetup(Test test, String configName) {
this(test, configName, null);
@ -541,11 +544,19 @@ public abstract class AbstractCollectionRegionAccessStrategyTestCase extends Abs
preferIPv4Stack = System.getProperty(PREFER_IPV4STACK);
System.setProperty(PREFER_IPV4STACK, "true");
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
localCfg = createConfiguration(configName, configResource);
localRegionFactory = CacheTestUtil.startRegionFactory(localCfg);
localRegionFactory = CacheTestUtil.startRegionFactory(
serviceRegistryHolder.getJdbcServicesImpl().getConnectionProvider(),
localCfg
);
remoteCfg = createConfiguration(configName, configResource);
remoteRegionFactory = CacheTestUtil.startRegionFactory(remoteCfg);
remoteRegionFactory = CacheTestUtil.startRegionFactory(
serviceRegistryHolder.getJdbcServicesImpl().getConnectionProvider(),
remoteCfg
);
}
@Override
@ -559,11 +570,18 @@ public abstract class AbstractCollectionRegionAccessStrategyTestCase extends Abs
System.setProperty(PREFER_IPV4STACK, preferIPv4Stack);
}
if (localRegionFactory != null)
localRegionFactory.stop();
try {
if (localRegionFactory != null)
localRegionFactory.stop();
if (remoteRegionFactory != null)
remoteRegionFactory.stop();
if (remoteRegionFactory != null)
remoteRegionFactory.stop();
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
}

View File

@ -54,7 +54,9 @@ public class TransactionalExtraAPITestCase extends AbstractNonFunctionalTestCase
if (getCollectionAccessStrategy() == null) {
Configuration cfg = createConfiguration();
InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
// Sleep a bit to avoid concurrent FLUSH problem
avoidConcurrentFlush();

View File

@ -41,8 +41,10 @@ import org.hibernate.cache.infinispan.impl.BaseRegion;
import org.hibernate.cache.infinispan.util.CacheAdapter;
import org.hibernate.cache.infinispan.util.FlagAdapter;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.cache.infinispan.AbstractNonFunctionalTestCase;
import org.hibernate.test.cache.infinispan.util.CacheTestUtil;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.hibernate.util.ComparableComparator;
import org.infinispan.transaction.tm.BatchModeTransactionManager;
@ -637,6 +639,7 @@ public abstract class AbstractEntityRegionAccessStrategyTestCase extends Abstrac
private static final String PREFER_IPV4STACK = "java.net.preferIPv4Stack";
private final String configName;
private String preferIPv4Stack;
private ServiceRegistryHolder serviceRegistryHolder;
public AccessStrategyTestSetup(Test test, String configName) {
super(test);
@ -658,22 +661,37 @@ public abstract class AbstractEntityRegionAccessStrategyTestCase extends Abstrac
preferIPv4Stack = System.getProperty(PREFER_IPV4STACK);
System.setProperty(PREFER_IPV4STACK, "true");
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
localCfg = createConfiguration(configName);
localRegionFactory = CacheTestUtil.startRegionFactory(localCfg);
localRegionFactory = CacheTestUtil.startRegionFactory(
serviceRegistryHolder.getJdbcServicesImpl().getConnectionProvider(),
localCfg
);
remoteCfg = createConfiguration(configName);
remoteRegionFactory = CacheTestUtil.startRegionFactory(remoteCfg);
remoteRegionFactory = CacheTestUtil.startRegionFactory(
serviceRegistryHolder.getJdbcServicesImpl().getConnectionProvider(),
remoteCfg
);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
if (localRegionFactory != null)
localRegionFactory.stop();
try {
if (localRegionFactory != null)
localRegionFactory.stop();
if (remoteRegionFactory != null)
remoteRegionFactory.stop();
if (remoteRegionFactory != null)
remoteRegionFactory.stop();
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
}

View File

@ -60,7 +60,9 @@ public class TransactionalExtraAPITestCase extends AbstractNonFunctionalTestCase
if (getEntityAccessStrategy() == null) {
Configuration cfg = createConfiguration();
InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory rf = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
// Sleep a bit to avoid concurrent FLUSH problem
avoidConcurrentFlush();

View File

@ -26,8 +26,10 @@ package org.hibernate.test.cache.infinispan.functional;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
@ -44,7 +46,7 @@ import org.hibernate.Session;
import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.infinispan.InfinispanRegionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.stat.SecondLevelCacheStatistics;
import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeTestCase;
import org.hibernate.test.cache.infinispan.functional.cluster.DualNodeConnectionProviderImpl;
@ -148,6 +150,11 @@ public class ConcurrentWriteTest extends SingleNodeTestCase {
cfg.setProperty(DualNodeTestCase.NODE_ID_PROP, DualNodeTestCase.LOCAL);
}
@Override
protected Map getConnectionProviderInjectionProperties() {
return Collections.singletonMap( DualNodeTestCase.NODE_ID_FIELD, DualNodeTestCase.LOCAL );
}
@Override
protected boolean getUseQueryCache() {
return true;

View File

@ -98,7 +98,7 @@ public class JndiRegionFactoryTestCase extends SingleNodeTestCase {
getEnvironment().getSessionFactory().close();
bindToJndi = false;
ExecutionEnvironment environment = new ExecutionEnvironment( this );
environment.initialize();
environment.initialize( getConnectionProviderInjectionProperties() );
setEnvironment(environment);
addEntityCheckCache();
JndiInfinispanRegionFactory regionFactory = (JndiInfinispanRegionFactory) ((SessionFactoryImplementor)

View File

@ -7,7 +7,7 @@ import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.infinispan.InfinispanRegionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.junit.functional.FunctionalTestCase;
import org.hibernate.stat.SecondLevelCacheStatistics;
import org.hibernate.stat.Statistics;

View File

@ -34,7 +34,7 @@ import org.hibernate.cache.infinispan.InfinispanRegionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.classic.Session;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.junit.functional.FunctionalTestCase;
import org.hibernate.stat.SecondLevelCacheStatistics;
import org.hibernate.test.cache.infinispan.functional.Contact;

View File

@ -28,8 +28,9 @@ import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.ConnectionProviderFactory;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.test.common.ConnectionProviderBuilder;
/**
* A {@link ConnectionProvider} implementation adding JTA-style transactionality around the returned
@ -38,7 +39,7 @@ import org.hibernate.connection.ConnectionProviderFactory;
* @author Brian Stansberry
*/
public class DualNodeConnectionProviderImpl implements ConnectionProvider {
private static ConnectionProvider actualConnectionProvider = ConnectionProviderFactory.newConnectionProvider();
private static ConnectionProvider actualConnectionProvider = ConnectionProviderBuilder.buildConnectionProvider();
private String nodeId;
private boolean isTransactional;
@ -46,10 +47,11 @@ public class DualNodeConnectionProviderImpl implements ConnectionProvider {
return actualConnectionProvider;
}
public void configure(Properties props) throws HibernateException {
nodeId = props.getProperty(DualNodeTestCase.NODE_ID_PROP);
if (nodeId == null)
throw new HibernateException(DualNodeTestCase.NODE_ID_PROP + " not configured");
public void setNodeId(String nodeId) throws HibernateException {
if (nodeId == null) {
throw new HibernateException( "nodeId not configured" );
}
this.nodeId = nodeId;
}
public Connection getConnection() throws SQLException {
@ -76,7 +78,9 @@ public class DualNodeConnectionProviderImpl implements ConnectionProvider {
}
public void close() throws HibernateException {
actualConnectionProvider.close();
if ( actualConnectionProvider instanceof Stoppable ) {
( ( Stoppable ) actualConnectionProvider ).stop();
}
}
public boolean supportsAggressiveRelease() {

View File

@ -21,6 +21,9 @@
*/
package org.hibernate.test.cache.infinispan.functional.cluster;
import java.util.Collections;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
@ -43,6 +46,7 @@ public abstract class DualNodeTestCase extends FunctionalTestCase {
private static final Log log = LogFactory.getLog(DualNodeTestCase.class);
public static final String NODE_ID_PROP = "hibernate.test.cluster.node.id";
public static final String NODE_ID_FIELD = "nodeId";
public static final String LOCAL = "local";
public static final String REMOTE = "remote";
private ExecutionEnvironment secondNodeEnvironment;
@ -71,11 +75,16 @@ public abstract class DualNodeTestCase extends FunctionalTestCase {
configureFirstNode(cfg);
}
@Override
protected Map getConnectionProviderInjectionProperties() {
return getFirstNodeConnectionProviderInjectionProperties();
}
@Override
protected void prepareTest() throws Exception {
log.info("Building second node locally managed execution env");
secondNodeEnvironment = new ExecutionEnvironment(new SecondNodeSettings());
secondNodeEnvironment.initialize();
secondNodeEnvironment.initialize( getSecondNodeConnectionProviderInjectionProperties() );
super.prepareTest();
}
@ -142,6 +151,10 @@ public abstract class DualNodeTestCase extends FunctionalTestCase {
cfg.setProperty(NODE_ID_PROP, LOCAL);
}
protected Map getFirstNodeConnectionProviderInjectionProperties() {
return Collections.singletonMap( NODE_ID_FIELD, LOCAL );
}
/**
* Apply any node-specific configurations to our second node.
*
@ -151,7 +164,11 @@ public abstract class DualNodeTestCase extends FunctionalTestCase {
protected void configureSecondNode(Configuration cfg) {
cfg.setProperty(NODE_ID_PROP, REMOTE);
}
protected Map getSecondNodeConnectionProviderInjectionProperties() {
return Collections.singletonMap( NODE_ID_FIELD, REMOTE );
}
protected void sleep(long ms) {
try {
Thread.sleep(ms);

View File

@ -90,7 +90,8 @@ public class QueryRegionImplTestCase extends AbstractGeneralDataRegionTestCase {
private void putDoesNotBlockGetTest() throws Exception {
Configuration cfg = createConfiguration();
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport());
// Sleep a bit to avoid concurrent FLUSH problem
avoidConcurrentFlush();
@ -175,7 +176,9 @@ public class QueryRegionImplTestCase extends AbstractGeneralDataRegionTestCase {
private void getDoesNotBlockPutTest() throws Exception {
Configuration cfg = createConfiguration();
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
// Sleep a bit to avoid concurrent FLUSH problem
avoidConcurrentFlush();

View File

@ -86,12 +86,16 @@ public class TimestampsRegionImplTestCase extends AbstractGeneralDataRegionTestC
public void testClearTimestampsRegionInIsolated() throws Exception {
Configuration cfg = createConfiguration();
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());
InfinispanRegionFactory regionFactory = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg, getCacheTestSupport()
);
// Sleep a bit to avoid concurrent FLUSH problem
avoidConcurrentFlush();
Configuration cfg2 = createConfiguration();
InfinispanRegionFactory regionFactory2 = CacheTestUtil.startRegionFactory(cfg2, getCacheTestSupport());
InfinispanRegionFactory regionFactory2 = CacheTestUtil.startRegionFactory(
getConnectionProvider(), cfg2, getCacheTestSupport()
);
// Sleep a bit to avoid concurrent FLUSH problem
avoidConcurrentFlush();

View File

@ -33,6 +33,8 @@ import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.stat.Statistics;
import org.hibernate.test.cache.infinispan.functional.Item;
import org.hibernate.test.common.ServiceRegistryHolder;
import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
@ -70,10 +72,12 @@ public class JBossStandaloneJtaExampleTest extends TestCase {
private static final JBossStandaloneJTAManagerLookup lookup = new JBossStandaloneJTAManagerLookup();
Context ctx;
Main jndiServer;
private ServiceRegistryHolder serviceRegistryHolder;
@Override
protected void setUp() throws Exception {
super.setUp();
serviceRegistryHolder = new ServiceRegistryHolder( Environment.getProperties() );
jndiServer = startJndiServer();
ctx = createJndiContext();
bindTransactionManager();
@ -83,9 +87,16 @@ public class JBossStandaloneJtaExampleTest extends TestCase {
@Override
protected void tearDown() throws Exception {
super.tearDown();
ctx.close();
jndiServer.stop();
try {
super.tearDown();
ctx.close();
jndiServer.stop();
}
finally {
if ( serviceRegistryHolder != null ) {
serviceRegistryHolder.destroy();
}
}
}
public void testPersistAndLoadUnderJta() throws Exception {
@ -290,6 +301,6 @@ public class JBossStandaloneJtaExampleTest extends TestCase {
Collection coll = (Collection) iter.next();
cfg.setCollectionCacheConcurrencyStrategy(coll.getRole(), "transactional");
}
return cfg.buildSessionFactory();
return cfg.buildSessionFactory( serviceRegistryHolder.getServiceRegistry() );
}
}

View File

@ -26,8 +26,9 @@ import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.connection.ConnectionProviderFactory;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.test.common.ConnectionProviderBuilder;
/**
* XaConnectionProvider.
@ -36,7 +37,7 @@ import org.hibernate.connection.ConnectionProviderFactory;
* @since 3.5
*/
public class XaConnectionProvider implements ConnectionProvider {
private static ConnectionProvider actualConnectionProvider = ConnectionProviderFactory.newConnectionProvider();
private static ConnectionProvider actualConnectionProvider = ConnectionProviderBuilder.buildConnectionProvider();
private boolean isTransactional;
public static ConnectionProvider getActualConnectionProvider() {
@ -69,7 +70,9 @@ public class XaConnectionProvider implements ConnectionProvider {
}
public void close() throws HibernateException {
actualConnectionProvider.close();
if ( actualConnectionProvider instanceof Stoppable ) {
( ( Stoppable ) actualConnectionProvider ).stop();
}
}
public boolean supportsAggressiveRelease() {

View File

@ -36,6 +36,8 @@ import org.hibernate.cache.infinispan.InfinispanRegionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.Settings;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.ServicesRegistry;
/**
* Utilities for cache testing.
@ -71,10 +73,11 @@ public class CacheTestUtil {
return cfg;
}
public static InfinispanRegionFactory startRegionFactory(Configuration cfg) throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
public static InfinispanRegionFactory startRegionFactory(ConnectionProvider connectionProvider,
Configuration cfg)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Settings settings = cfg.buildSettings();
Settings settings = cfg.buildSettings( connectionProvider );
Properties properties = cfg.getProperties();
String factoryType = cfg.getProperty(Environment.CACHE_REGION_FACTORY);
@ -86,9 +89,11 @@ public class CacheTestUtil {
return regionFactory;
}
public static InfinispanRegionFactory startRegionFactory(Configuration cfg, CacheTestSupport testSupport)
public static InfinispanRegionFactory startRegionFactory(ConnectionProvider connectionProvider,
Configuration cfg,
CacheTestSupport testSupport)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
InfinispanRegionFactory factory = startRegionFactory(cfg);
InfinispanRegionFactory factory = startRegionFactory(connectionProvider, cfg);
testSupport.registerFactory(factory);
return factory;
}