HHH-10907 - Fix connection leak problem in hibernate-core tests

(cherry picked from commit f5e10c29eb)
This commit is contained in:
Vlad Mihalcea 2016-07-13 21:19:56 +03:00 committed by Gail Badner
parent b4016f92f5
commit 77f452fad2
32 changed files with 778 additions and 517 deletions

View File

@ -29,11 +29,13 @@ import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.ServiceRegistryImplementor; import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool; import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool;
import org.hibernate.tool.schema.internal.SchemaCreatorImpl; import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.tool.schema.internal.SchemaDropperImpl; import org.hibernate.tool.schema.internal.SchemaDropperImpl;
import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase; import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.test.util.DdlTransactionIsolatorTestingImpl; import org.hibernate.test.util.DdlTransactionIsolatorTestingImpl;
import org.junit.Test; import org.junit.Test;
@ -69,6 +71,16 @@ public abstract class AbstractMultiTenancyTest extends BaseUnitTestCase {
} }
//end::multitenacy-hibernate-MultiTenantConnectionProvider-example[] //end::multitenacy-hibernate-MultiTenantConnectionProvider-example[]
@AfterClassOnce
public void destroy() {
sessionFactory.close();
for ( ConnectionProvider connectionProvider : connectionProviderMap.values() ) {
if ( connectionProvider instanceof Stoppable ) {
( (Stoppable) connectionProvider ).stop();
}
}
}
//tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[] //tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[]
protected void registerConnectionProvider(String tenantIdentifier) { protected void registerConnectionProvider(String tenantIdentifier) {

View File

@ -74,6 +74,7 @@ public class TransactionsTest extends BaseEntityManagerFunctionalTestCase {
} }
finally { finally {
session.close(); session.close();
sessionFactory.close();
} }
//end::transactions-api-jdbc-example[] //end::transactions-api-jdbc-example[]
} }
@ -123,6 +124,7 @@ public class TransactionsTest extends BaseEntityManagerFunctionalTestCase {
} }
finally { finally {
session.close(); session.close();
sessionFactory.close();
} }
//end::transactions-api-cmt-example[] //end::transactions-api-cmt-example[]
} }
@ -176,6 +178,7 @@ public class TransactionsTest extends BaseEntityManagerFunctionalTestCase {
} }
finally { finally {
session.close(); session.close();
sessionFactory.close();
} }
//end::transactions-api-bmt-example[] //end::transactions-api-bmt-example[]
} }

View File

@ -30,61 +30,76 @@ import static org.junit.Assert.assertTrue;
*/ */
public class C3P0ConnectionProviderTest extends BaseCoreFunctionalTestCase { public class C3P0ConnectionProviderTest extends BaseCoreFunctionalTestCase {
@Test @Override
public void testC3P0isDefaultWhenThereIsC3P0Properties() { protected void releaseSessionFactory() {
JdbcServices jdbcServices = serviceRegistry().getService( JdbcServices.class ); super.releaseSessionFactory();
ConnectionProviderJdbcConnectionAccess connectionAccess = try {
assertTyping( //c3p0 does not close physical connections right away, so without this hack a connection leak false alarm is triggered.
ConnectionProviderJdbcConnectionAccess.class, Thread.sleep( 100 );
jdbcServices.getBootstrapJdbcConnectionAccess() }
catch ( InterruptedException e ) {
}
}
@Test
public void testC3P0isDefaultWhenThereIsC3P0Properties() {
JdbcServices jdbcServices = serviceRegistry().getService( JdbcServices.class );
ConnectionProviderJdbcConnectionAccess connectionAccess =
assertTyping(
ConnectionProviderJdbcConnectionAccess.class,
jdbcServices.getBootstrapJdbcConnectionAccess()
);
assertTrue( connectionAccess.getConnectionProvider() instanceof C3P0ConnectionProvider );
}
@Test
public void testHHH6635() throws Exception {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> set = mBeanServer.queryNames( null, null );
boolean mbeanfound = false;
for ( ObjectName obj : set ) {
if ( obj.getKeyPropertyListString().indexOf( "PooledDataSource" ) > 0 ) {
mbeanfound = true;
// see according c3p0 settings in META-INF/persistence.xml
int actual_minPoolSize = (Integer) mBeanServer.getAttribute( obj, "minPoolSize" );
assertEquals( 50, actual_minPoolSize );
int actual_initialPoolSize = (Integer) mBeanServer.getAttribute( obj, "initialPoolSize" );
assertEquals( 50, actual_initialPoolSize );
int actual_maxPoolSize = (Integer) mBeanServer.getAttribute( obj, "maxPoolSize" );
assertEquals( 800, actual_maxPoolSize );
int actual_maxStatements = (Integer) mBeanServer.getAttribute( obj, "maxStatements" );
assertEquals( 50, actual_maxStatements );
int actual_maxIdleTime = (Integer) mBeanServer.getAttribute( obj, "maxIdleTime" );
assertEquals( 300, actual_maxIdleTime );
int actual_idleConnectionTestPeriod = (Integer) mBeanServer.getAttribute(
obj,
"idleConnectionTestPeriod"
); );
assertTrue( connectionAccess.getConnectionProvider() instanceof C3P0ConnectionProvider ); assertEquals( 3000, actual_idleConnectionTestPeriod );
break;
}
}
} assertTrue( "PooledDataSource BMean not found, please verify version of c3p0", mbeanfound );
}
@Test @Test @TestForIssue(jiraKey="HHH-9498")
public void testHHH6635() throws Exception { public void testIsolationPropertyCouldBeEmpty() {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); C3P0ConnectionProvider provider = new C3P0ConnectionProvider();
Set<ObjectName> set = mBeanServer.queryNames( null, null ); try {
boolean mbeanfound = false; Properties configuration = new Properties();
for ( ObjectName obj : set ) { configuration.setProperty( Environment.ISOLATION, "" );
if ( obj.getKeyPropertyListString().indexOf( "PooledDataSource" ) > 0 ) { provider.configure( configuration );
mbeanfound = true; }
finally {
// see according c3p0 settings in META-INF/persistence.xml provider.stop();
}
int actual_minPoolSize = (Integer) mBeanServer.getAttribute( obj, "minPoolSize" ); }
assertEquals( 50, actual_minPoolSize );
int actual_initialPoolSize = (Integer) mBeanServer.getAttribute( obj, "initialPoolSize" );
assertEquals( 50, actual_initialPoolSize );
int actual_maxPoolSize = (Integer) mBeanServer.getAttribute( obj, "maxPoolSize" );
assertEquals( 800, actual_maxPoolSize );
int actual_maxStatements = (Integer) mBeanServer.getAttribute( obj, "maxStatements" );
assertEquals( 50, actual_maxStatements );
int actual_maxIdleTime = (Integer) mBeanServer.getAttribute( obj, "maxIdleTime" );
assertEquals( 300, actual_maxIdleTime );
int actual_idleConnectionTestPeriod = (Integer) mBeanServer.getAttribute(
obj,
"idleConnectionTestPeriod"
);
assertEquals( 3000, actual_idleConnectionTestPeriod );
break;
}
}
assertTrue( "PooledDataSource BMean not found, please verify version of c3p0", mbeanfound );
}
@Test @TestForIssue(jiraKey="HHH-9498")
public void testIsolationPropertyCouldBeEmpty() {
Properties configuration = new Properties();
configuration.setProperty( Environment.ISOLATION, "" );
C3P0ConnectionProvider provider = new C3P0ConnectionProvider();
provider.configure( configuration );
}
} }

View File

@ -214,6 +214,15 @@ public class BootstrapServiceRegistryImpl
destroy( classLoaderServiceBinding ); destroy( classLoaderServiceBinding );
destroy( strategySelectorBinding ); destroy( strategySelectorBinding );
destroy( integratorServiceBinding ); destroy( integratorServiceBinding );
if ( childRegistries != null ) {
for(ServiceRegistry serviceRegistry : childRegistries) {
if(serviceRegistry instanceof ServiceRegistryImplementor) {
ServiceRegistryImplementor serviceRegistryImplementor = (ServiceRegistryImplementor) serviceRegistry;
serviceRegistryImplementor.destroy();
}
}
}
} }
private void destroy(ServiceBinding serviceBinding) { private void destroy(ServiceBinding serviceBinding) {

View File

@ -227,10 +227,10 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
this.name = sfName; this.name = sfName;
try { try {
uuid = (String) UUID_GENERATOR.generate(null, null); uuid = (String) UUID_GENERATOR.generate( null, null );
} }
catch (Exception e) { catch (Exception e) {
throw new AssertionFailure("Could not generate UUID"); throw new AssertionFailure( "Could not generate UUID" );
} }
this.properties = new Properties(); this.properties = new Properties();
@ -273,260 +273,286 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
} }
final IntegratorObserver integratorObserver = new IntegratorObserver(); final IntegratorObserver integratorObserver = new IntegratorObserver();
this.observer.addObserver( integratorObserver ); this.observer.addObserver( integratorObserver );
for ( Integrator integrator : serviceRegistry.getService( IntegratorService.class ).getIntegrators() ) {
integrator.integrate( metadata, this, this.serviceRegistry );
integratorObserver.integrators.add( integrator );
}
//Generators: try {
for ( Integrator integrator : serviceRegistry.getService( IntegratorService.class ).getIntegrators() ) {
this.identifierGenerators = new HashMap<String, IdentifierGenerator>(); integrator.integrate( metadata, this, this.serviceRegistry );
for ( PersistentClass model : metadata.getEntityBindings() ) { integratorObserver.integrators.add( integrator );
if ( !model.isInherited() ) {
IdentifierGenerator generator = model.getIdentifier().createIdentifierGenerator(
metadata.getIdentifierGeneratorFactory(),
getDialect(),
settings.getDefaultCatalogName(),
settings.getDefaultSchemaName(),
(RootClass) model
);
identifierGenerators.put( model.getEntityName(), generator );
}
}
this.imports = new HashMap<String,String>( metadata.getImports() );
///////////////////////////////////////////////////////////////////////
// Prepare persisters and link them up with their cache
// region/access-strategy
final PersisterCreationContext persisterCreationContext = new PersisterCreationContext() {
@Override
public SessionFactoryImplementor getSessionFactory() {
return SessionFactoryImpl.this;
} }
@Override //Generators:
public MetadataImplementor getMetadata() {
return metadata;
}
};
final RegionFactory regionFactory = cacheAccess.getRegionFactory(); this.identifierGenerators = new HashMap<String, IdentifierGenerator>();
final String cacheRegionPrefix = settings.getCacheRegionPrefix() == null ? "" : settings.getCacheRegionPrefix() + "."; for ( PersistentClass model : metadata.getEntityBindings() ) {
final PersisterFactory persisterFactory = serviceRegistry.getService( PersisterFactory.class ); if ( !model.isInherited() ) {
IdentifierGenerator generator = model.getIdentifier().createIdentifierGenerator(
// todo : consider removing this silliness and just have EntityPersister directly implement ClassMetadata metadata.getIdentifierGeneratorFactory(),
// EntityPersister.getClassMetadata() for the internal impls simply "return this"; getDialect(),
// collapsing those would allow us to remove this "extra" Map settings.getDefaultCatalogName(),
// settings.getDefaultSchemaName(),
// todo : similar for CollectionPersister/CollectionMetadata (RootClass) model
);
this.entityPersisters = new HashMap<String,EntityPersister>(); identifierGenerators.put( model.getEntityName(), generator );
Map<String,ClassMetadata> inFlightClassMetadataMap = new HashMap<String,ClassMetadata>();
this.entityProxyInterfaceMap = CollectionHelper.concurrentMap( metadata.getEntityBindings().size() );
for ( final PersistentClass model : metadata.getEntityBindings() ) {
final String cacheRegionName = cacheRegionPrefix + model.getRootClass().getCacheRegionName();
// cache region is defined by the root-class in the hierarchy...
final EntityRegionAccessStrategy accessStrategy = determineEntityRegionAccessStrategy(
regionFactory,
cacheAccessStrategiesMap,
model,
cacheRegionName
);
final NaturalIdRegionAccessStrategy naturalIdAccessStrategy = determineNaturalIdRegionAccessStrategy(
regionFactory,
cacheRegionPrefix,
cacheAccessStrategiesMap,
model
);
final EntityPersister cp = persisterFactory.createEntityPersister(
model,
accessStrategy,
naturalIdAccessStrategy,
persisterCreationContext
);
entityPersisters.put( model.getEntityName(), cp );
inFlightClassMetadataMap.put( model.getEntityName(), cp.getClassMetadata() );
if ( cp.getConcreteProxyClass() != null
&& cp.getConcreteProxyClass().isInterface()
&& !Map.class.isAssignableFrom( cp.getConcreteProxyClass() )
&& cp.getMappedClass() != cp.getConcreteProxyClass() ) {
// IMPL NOTE : we exclude Map based proxy interfaces here because that should
// indicate MAP entity mode.0
if ( cp.getMappedClass().equals( cp.getConcreteProxyClass() ) ) {
// this part handles an odd case in the Hibernate test suite where we map an interface
// as the class and the proxy. I cannot think of a real life use case for that
// specific test, but..
LOG.debugf( "Entity [%s] mapped same interface [%s] as class and proxy", cp.getEntityName(), cp.getMappedClass() );
} }
else { }
final String old = entityProxyInterfaceMap.put( cp.getConcreteProxyClass(), cp.getEntityName() );
if ( old != null ) { this.imports = new HashMap<String, String>( metadata.getImports() );
throw new HibernateException(
String.format( ///////////////////////////////////////////////////////////////////////
Locale.ENGLISH, // Prepare persisters and link them up with their cache
"Multiple entities [%s, %s] named the same interface [%s] as their proxy which is not supported", // region/access-strategy
old,
cp.getEntityName(), final PersisterCreationContext persisterCreationContext = new PersisterCreationContext() {
cp.getConcreteProxyClass().getName() @Override
) public SessionFactoryImplementor getSessionFactory() {
return SessionFactoryImpl.this;
}
@Override
public MetadataImplementor getMetadata() {
return metadata;
}
};
final RegionFactory regionFactory = cacheAccess.getRegionFactory();
final String cacheRegionPrefix = settings.getCacheRegionPrefix() == null ?
"" :
settings.getCacheRegionPrefix() + ".";
final PersisterFactory persisterFactory = serviceRegistry.getService( PersisterFactory.class );
// todo : consider removing this silliness and just have EntityPersister directly implement ClassMetadata
// EntityPersister.getClassMetadata() for the internal impls simply "return this";
// collapsing those would allow us to remove this "extra" Map
//
// todo : similar for CollectionPersister/CollectionMetadata
this.entityPersisters = new HashMap<String, EntityPersister>();
Map<String, ClassMetadata> inFlightClassMetadataMap = new HashMap<String, ClassMetadata>();
this.entityProxyInterfaceMap = CollectionHelper.concurrentMap( metadata.getEntityBindings().size() );
for ( final PersistentClass model : metadata.getEntityBindings() ) {
final String cacheRegionName = cacheRegionPrefix + model.getRootClass().getCacheRegionName();
// cache region is defined by the root-class in the hierarchy...
final EntityRegionAccessStrategy accessStrategy = determineEntityRegionAccessStrategy(
regionFactory,
cacheAccessStrategiesMap,
model,
cacheRegionName
);
final NaturalIdRegionAccessStrategy naturalIdAccessStrategy = determineNaturalIdRegionAccessStrategy(
regionFactory,
cacheRegionPrefix,
cacheAccessStrategiesMap,
model
);
final EntityPersister cp = persisterFactory.createEntityPersister(
model,
accessStrategy,
naturalIdAccessStrategy,
persisterCreationContext
);
entityPersisters.put( model.getEntityName(), cp );
inFlightClassMetadataMap.put( model.getEntityName(), cp.getClassMetadata() );
if ( cp.getConcreteProxyClass() != null
&& cp.getConcreteProxyClass().isInterface()
&& !Map.class.isAssignableFrom( cp.getConcreteProxyClass() )
&& cp.getMappedClass() != cp.getConcreteProxyClass() ) {
// IMPL NOTE : we exclude Map based proxy interfaces here because that should
// indicate MAP entity mode.0
if ( cp.getMappedClass().equals( cp.getConcreteProxyClass() ) ) {
// this part handles an odd case in the Hibernate test suite where we map an interface
// as the class and the proxy. I cannot think of a real life use case for that
// specific test, but..
LOG.debugf(
"Entity [%s] mapped same interface [%s] as class and proxy",
cp.getEntityName(),
cp.getMappedClass()
); );
} }
} else {
} final String old = entityProxyInterfaceMap.put(
} cp.getConcreteProxyClass(),
this.classMetadata = Collections.unmodifiableMap( inFlightClassMetadataMap ); cp.getEntityName()
);
this.collectionPersisters = new HashMap<String,CollectionPersister>(); if ( old != null ) {
Map<String,Set<String>> inFlightEntityToCollectionRoleMap = new HashMap<String,Set<String>>(); throw new HibernateException(
Map<String,CollectionMetadata> tmpCollectionMetadata = new HashMap<String,CollectionMetadata>(); String.format(
for ( final Collection model : metadata.getCollectionBindings() ) { Locale.ENGLISH,
final String cacheRegionName = cacheRegionPrefix + model.getCacheRegionName(); "Multiple entities [%s, %s] named the same interface [%s] as their proxy which is not supported",
final CollectionRegionAccessStrategy accessStrategy = determineCollectionRegionAccessStrategy( old,
regionFactory, cp.getEntityName(),
cacheAccessStrategiesMap, cp.getConcreteProxyClass().getName()
model, )
cacheRegionName); );
}
final CollectionPersister persister = persisterFactory.createCollectionPersister(
model,
accessStrategy,
persisterCreationContext
);
collectionPersisters.put( model.getRole(), persister );
tmpCollectionMetadata.put( model.getRole(), persister.getCollectionMetadata() );
Type indexType = persister.getIndexType();
if ( indexType != null && indexType.isAssociationType() && !indexType.isAnyType() ) {
String entityName = ( ( AssociationType ) indexType ).getAssociatedEntityName( this );
Set<String> roles = inFlightEntityToCollectionRoleMap.get( entityName );
if ( roles == null ) {
roles = new HashSet<String>();
inFlightEntityToCollectionRoleMap.put( entityName, roles );
}
roles.add( persister.getRole() );
}
Type elementType = persister.getElementType();
if ( elementType.isAssociationType() && !elementType.isAnyType() ) {
String entityName = ( ( AssociationType ) elementType ).getAssociatedEntityName( this );
Set<String> roles = inFlightEntityToCollectionRoleMap.get( entityName );
if ( roles == null ) {
roles = new HashSet<String>();
inFlightEntityToCollectionRoleMap.put( entityName, roles );
}
roles.add( persister.getRole() );
}
}
this.collectionMetadata = Collections.unmodifiableMap( tmpCollectionMetadata );
for ( Map.Entry<String,Set<String>> entityToCollectionRoleMapEntry : inFlightEntityToCollectionRoleMap.entrySet() ) {
entityToCollectionRoleMapEntry.setValue(
Collections.unmodifiableSet( entityToCollectionRoleMapEntry.getValue() )
);
}
this.collectionRolesByEntityParticipant = Collections.unmodifiableMap( inFlightEntityToCollectionRoleMap );
//Named Queries:
this.namedQueryRepository = metadata.buildNamedQueryRepository( this );
// after *all* persisters and named queries are registered
for ( EntityPersister persister : entityPersisters.values() ) {
persister.generateEntityDefinition();
}
for ( EntityPersister persister : entityPersisters.values() ) {
persister.postInstantiate();
registerEntityNameResolvers( persister );
}
for ( CollectionPersister persister : collectionPersisters.values() ) {
persister.postInstantiate();
}
LOG.debug( "Instantiated session factory" );
settings.getMultiTableBulkIdStrategy().prepare(
jdbcServices,
buildLocalConnectionAccess(),
metadata,
sessionFactoryOptions
);
SchemaManagementToolCoordinator.process(
metadata,
serviceRegistry,
properties,
new DelayedDropRegistry() {
@Override
public void registerOnCloseAction(DelayedDropAction action) {
SessionFactoryImpl.this.delayedDropAction = action;
} }
} }
); }
this.classMetadata = Collections.unmodifiableMap( inFlightClassMetadataMap );
currentSessionContext = buildCurrentSessionContext(); this.collectionPersisters = new HashMap<String, CollectionPersister>();
Map<String, Set<String>> inFlightEntityToCollectionRoleMap = new HashMap<String, Set<String>>();
Map<String, CollectionMetadata> tmpCollectionMetadata = new HashMap<String, CollectionMetadata>();
for ( final Collection model : metadata.getCollectionBindings() ) {
final String cacheRegionName = cacheRegionPrefix + model.getCacheRegionName();
final CollectionRegionAccessStrategy accessStrategy = determineCollectionRegionAccessStrategy(
regionFactory,
cacheAccessStrategiesMap,
model,
cacheRegionName
);
//checking for named queries final CollectionPersister persister = persisterFactory.createCollectionPersister(
if ( settings.isNamedQueryStartupCheckingEnabled() ) { model,
final Map<String,HibernateException> errors = checkNamedQueries(); accessStrategy,
if ( ! errors.isEmpty() ) { persisterCreationContext
StringBuilder failingQueries = new StringBuilder( "Errors in named queries: " ); );
String sep = ""; collectionPersisters.put( model.getRole(), persister );
for ( Map.Entry<String,HibernateException> entry : errors.entrySet() ) { tmpCollectionMetadata.put( model.getRole(), persister.getCollectionMetadata() );
LOG.namedQueryError( entry.getKey(), entry.getValue() ); Type indexType = persister.getIndexType();
failingQueries.append( sep ).append( entry.getKey() ); if ( indexType != null && indexType.isAssociationType() && !indexType.isAnyType() ) {
sep = ", "; String entityName = ( (AssociationType) indexType ).getAssociatedEntityName( this );
Set<String> roles = inFlightEntityToCollectionRoleMap.get( entityName );
if ( roles == null ) {
roles = new HashSet<String>();
inFlightEntityToCollectionRoleMap.put( entityName, roles );
}
roles.add( persister.getRole() );
} }
throw new HibernateException( failingQueries.toString() ); Type elementType = persister.getElementType();
if ( elementType.isAssociationType() && !elementType.isAnyType() ) {
String entityName = ( (AssociationType) elementType ).getAssociatedEntityName( this );
Set<String> roles = inFlightEntityToCollectionRoleMap.get( entityName );
if ( roles == null ) {
roles = new HashSet<String>();
inFlightEntityToCollectionRoleMap.put( entityName, roles );
}
roles.add( persister.getRole() );
}
}
this.collectionMetadata = Collections.unmodifiableMap( tmpCollectionMetadata );
for ( Map.Entry<String, Set<String>> entityToCollectionRoleMapEntry : inFlightEntityToCollectionRoleMap.entrySet() ) {
entityToCollectionRoleMapEntry.setValue(
Collections.unmodifiableSet( entityToCollectionRoleMapEntry.getValue() )
);
}
this.collectionRolesByEntityParticipant = Collections.unmodifiableMap( inFlightEntityToCollectionRoleMap );
//Named Queries:
this.namedQueryRepository = metadata.buildNamedQueryRepository( this );
// after *all* persisters and named queries are registered
for ( EntityPersister persister : entityPersisters.values() ) {
persister.generateEntityDefinition();
}
for ( EntityPersister persister : entityPersisters.values() ) {
persister.postInstantiate();
registerEntityNameResolvers( persister );
}
for ( CollectionPersister persister : collectionPersisters.values() ) {
persister.postInstantiate();
}
LOG.debug( "Instantiated session factory" );
settings.getMultiTableBulkIdStrategy().prepare(
jdbcServices,
buildLocalConnectionAccess(),
metadata,
sessionFactoryOptions
);
SchemaManagementToolCoordinator.process(
metadata,
serviceRegistry,
properties,
new DelayedDropRegistry() {
@Override
public void registerOnCloseAction(DelayedDropAction action) {
SessionFactoryImpl.this.delayedDropAction = action;
}
}
);
currentSessionContext = buildCurrentSessionContext();
//checking for named queries
if ( settings.isNamedQueryStartupCheckingEnabled() ) {
final Map<String, HibernateException> errors = checkNamedQueries();
if ( !errors.isEmpty() ) {
StringBuilder failingQueries = new StringBuilder( "Errors in named queries: " );
String sep = "";
for ( Map.Entry<String, HibernateException> entry : errors.entrySet() ) {
LOG.namedQueryError( entry.getKey(), entry.getValue() );
failingQueries.append( sep ).append( entry.getKey() );
sep = ", ";
}
throw new HibernateException( failingQueries.toString() );
}
}
// this needs to happen after persisters are all ready to go...
this.fetchProfiles = new HashMap<String, FetchProfile>();
for ( org.hibernate.mapping.FetchProfile mappingProfile : metadata.getFetchProfiles() ) {
final FetchProfile fetchProfile = new FetchProfile( mappingProfile.getName() );
for ( org.hibernate.mapping.FetchProfile.Fetch mappingFetch : mappingProfile.getFetches() ) {
// resolve the persister owning the fetch
final String entityName = getImportedClassName( mappingFetch.getEntity() );
final EntityPersister owner = entityName == null
? null
: entityPersisters.get( entityName );
if ( owner == null ) {
throw new HibernateException(
"Unable to resolve entity reference [" + mappingFetch.getEntity()
+ "] in fetch profile [" + fetchProfile.getName() + "]"
);
}
// validate the specified association fetch
Type associationType = owner.getPropertyType( mappingFetch.getAssociation() );
if ( associationType == null || !associationType.isAssociationType() ) {
throw new HibernateException( "Fetch profile [" + fetchProfile.getName() + "] specified an invalid association" );
}
// resolve the style
final Fetch.Style fetchStyle = Fetch.Style.parse( mappingFetch.getStyle() );
// then construct the fetch instance...
fetchProfile.addFetch( new Association( owner, mappingFetch.getAssociation() ), fetchStyle );
( (Loadable) owner ).registerAffectingFetchProfile( fetchProfile.getName() );
}
fetchProfiles.put( fetchProfile.getName(), fetchProfile );
}
this.observer.sessionFactoryCreated( this );
SessionFactoryRegistry.INSTANCE.addSessionFactory(
uuid,
name,
settings.isSessionFactoryNameAlsoJndiName(),
this,
serviceRegistry.getService( JndiService.class )
);
}
catch (Exception e) {
for ( Integrator integrator : serviceRegistry.getService( IntegratorService.class ).getIntegrators() ) {
integrator.disintegrate( this, serviceRegistry );
integratorObserver.integrators.remove( integrator );
}
serviceRegistry.destroy();
if ( RuntimeException.class.isInstance( e ) ) {
throw (RuntimeException) e;
}
else {
throw new HibernateException( e );
} }
} }
// this needs to happen after persisters are all ready to go...
this.fetchProfiles = new HashMap<String,FetchProfile>();
for ( org.hibernate.mapping.FetchProfile mappingProfile : metadata.getFetchProfiles() ) {
final FetchProfile fetchProfile = new FetchProfile( mappingProfile.getName() );
for ( org.hibernate.mapping.FetchProfile.Fetch mappingFetch : mappingProfile.getFetches() ) {
// resolve the persister owning the fetch
final String entityName = getImportedClassName( mappingFetch.getEntity() );
final EntityPersister owner = entityName == null
? null
: entityPersisters.get( entityName );
if ( owner == null ) {
throw new HibernateException(
"Unable to resolve entity reference [" + mappingFetch.getEntity()
+ "] in fetch profile [" + fetchProfile.getName() + "]"
);
}
// validate the specified association fetch
Type associationType = owner.getPropertyType( mappingFetch.getAssociation() );
if ( associationType == null || !associationType.isAssociationType() ) {
throw new HibernateException( "Fetch profile [" + fetchProfile.getName() + "] specified an invalid association" );
}
// resolve the style
final Fetch.Style fetchStyle = Fetch.Style.parse( mappingFetch.getStyle() );
// then construct the fetch instance...
fetchProfile.addFetch( new Association( owner, mappingFetch.getAssociation() ), fetchStyle );
((Loadable) owner).registerAffectingFetchProfile( fetchProfile.getName() );
}
fetchProfiles.put( fetchProfile.getName(), fetchProfile );
}
this.observer.sessionFactoryCreated( this );
SessionFactoryRegistry.INSTANCE.addSessionFactory(
uuid,
name,
settings.isSessionFactoryNameAlsoJndiName(),
this,
serviceRegistry.getService( JndiService.class )
);
} }
private void applyCfgXmlValues(LoadedConfig aggregatedConfig, SessionFactoryServiceRegistry serviceRegistry) { private void applyCfgXmlValues(LoadedConfig aggregatedConfig, SessionFactoryServiceRegistry serviceRegistry) {

View File

@ -13,6 +13,7 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import javax.persistence.OptimisticLockException;
import org.hibernate.AnnotationException; import org.hibernate.AnnotationException;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
@ -21,6 +22,7 @@ import org.hibernate.Query;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.TeradataDialect; import org.hibernate.dialect.TeradataDialect;
@ -641,19 +643,26 @@ public class BasicHibernateAnnotationsTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testTypeDefWithoutNameAndDefaultForTypeAttributes() { public void testTypeDefWithoutNameAndDefaultForTypeAttributes() {
SessionFactory sf=null; SessionFactory sf = null;
StandardServiceRegistryImpl ssr = null;
try { try {
Configuration config = new Configuration(); Configuration config = new Configuration();
config.addAnnotatedClass(LocalContactDetails.class); config.addAnnotatedClass( LocalContactDetails.class );
sf = config.buildSessionFactory( ServiceRegistryBuilder.buildServiceRegistry( config.getProperties() ) ); ssr = ServiceRegistryBuilder.buildServiceRegistry( config.getProperties() );
fail("Did not throw expected exception"); sf = config.buildSessionFactory( ssr );
fail( "Did not throw expected exception" );
} }
catch( AnnotationException ex ) { catch ( AnnotationException ex ) {
assertEquals( assertEquals(
"Either name or defaultForType (or both) attribute should be set in TypeDef having typeClass org.hibernate.test.annotations.entity.PhoneNumberType", "Either name or defaultForType (or both) attribute should be set in TypeDef having typeClass org.hibernate.test.annotations.entity.PhoneNumberType",
ex.getMessage()); ex.getMessage()
} finally { );
if( sf != null){ }
finally {
if ( ssr != null ) {
ssr.destroy();
}
if ( sf != null ) {
sf.close(); sf.close();
} }
} }

View File

@ -10,6 +10,8 @@ import java.io.InputStream;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
@ -85,6 +87,12 @@ public class FetchProfileTest extends BaseUnitTestCase {
catch ( MappingException e ) { catch ( MappingException e ) {
log.trace("success"); log.trace("success");
} }
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Test @Test
@ -101,6 +109,12 @@ public class FetchProfileTest extends BaseUnitTestCase {
catch ( MappingException e ) { catch ( MappingException e ) {
log.trace("success"); log.trace("success");
} }
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Test @Test
@ -117,6 +131,12 @@ public class FetchProfileTest extends BaseUnitTestCase {
catch ( MappingException e ) { catch ( MappingException e ) {
log.trace("success"); log.trace("success");
} }
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Test @Test
@ -152,6 +172,12 @@ public class FetchProfileTest extends BaseUnitTestCase {
catch ( MappingException e ) { catch ( MappingException e ) {
log.trace("success"); log.trace("success");
} }
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Test @Test

View File

@ -9,38 +9,53 @@
package org.hibernate.test.annotations.fkcircularity; package org.hibernate.test.annotations.fkcircularity;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test; import org.junit.Test;
import org.jboss.logging.Logger;
/** /**
* Test case for ANN-722 and ANN-730. * Test case for ANN-722 and ANN-730.
* *
* @author Hardy Ferentschik * @author Hardy Ferentschik
*/ */
public class FkCircularityTest extends BaseUnitTestCase { public class FkCircularityTest extends BaseUnitTestCase {
private static final Logger log = Logger.getLogger( FkCircularityTest.class );
@Test @Test
public void testJoinedSublcassesInPK() { public void testJoinedSublcassesInPK() {
new MetadataSources() MetadataSources metadataSources = new MetadataSources()
.addAnnotatedClass(A.class) .addAnnotatedClass(A.class)
.addAnnotatedClass(B.class) .addAnnotatedClass(B.class)
.addAnnotatedClass(C.class) .addAnnotatedClass(C.class)
.addAnnotatedClass(D.class) .addAnnotatedClass(D.class);
.buildMetadata(); try {
metadataSources.buildMetadata();
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Test @Test
public void testDeepJoinedSuclassesHierachy() { public void testDeepJoinedSuclassesHierachy() {
new MetadataSources() MetadataSources metadataSources = new MetadataSources()
.addAnnotatedClass(ClassA.class) .addAnnotatedClass(ClassA.class)
.addAnnotatedClass(ClassB.class) .addAnnotatedClass(ClassB.class)
.addAnnotatedClass(ClassC.class) .addAnnotatedClass(ClassC.class)
.addAnnotatedClass(ClassD.class) .addAnnotatedClass(ClassD.class);
.buildMetadata(); try {
metadataSources.buildMetadata();
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
} }

View File

@ -8,12 +8,16 @@ package org.hibernate.test.annotations.immutable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.persistence.PersistenceException;
import org.hibernate.AnnotationException; import org.hibernate.AnnotationException;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test; import org.junit.Test;
@ -136,12 +140,19 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testMisplacedImmutableAnnotation() { public void testMisplacedImmutableAnnotation() {
MetadataSources metadataSources = new MetadataSources().addAnnotatedClass( Foobar.class );
try { try {
new MetadataSources().addAnnotatedClass( Foobar.class ).buildMetadata(); metadataSources.buildMetadata();
fail( "Expecting exception due to misplaced @Immutable annotation"); fail( "Expecting exception due to misplaced @Immutable annotation");
} }
catch (AnnotationException ignore) { catch (AnnotationException ignore) {
} }
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Override @Override

View File

@ -38,9 +38,6 @@ public class OrmVersion1SupportedTest extends BaseCoreFunctionalTestCase {
public void testOrm1Support() { public void testOrm1Support() {
Triggerable triggerable = logInspection.watchForLogMessages( "HHH00196" ); Triggerable triggerable = logInspection.watchForLogMessages( "HHH00196" );
// need to call buildSessionFactory, because this test is not using org.hibernate.testing.junit4.CustomRunner
buildSessionFactory();
Session s = openSession(); Session s = openSession();
Transaction tx = s.beginTransaction(); Transaction tx = s.beginTransaction();
Light light = new Light(); Light light = new Light();
@ -54,9 +51,6 @@ public class OrmVersion1SupportedTest extends BaseCoreFunctionalTestCase {
s.close(); s.close();
assertFalse( triggerable.wasTriggered() ); assertFalse( triggerable.wasTriggered() );
// which means we also need to close it manually
releaseSessionFactory();
} }
@Override @Override

View File

@ -1,11 +1,8 @@
package org.hibernate.test.bytecode.enhancement.access; package org.hibernate.test.bytecode.enhancement.access;
import org.hibernate.Session; import java.util.LinkedHashMap;
import org.hibernate.cfg.Configuration; import java.util.Map;
import org.hibernate.cfg.Environment; import java.util.stream.Collectors;
import org.hibernate.test.bytecode.enhancement.AbstractEnhancerTestTask;
import org.junit.Assert;
import javax.persistence.Access; import javax.persistence.Access;
import javax.persistence.AccessType; import javax.persistence.AccessType;
import javax.persistence.Column; import javax.persistence.Column;
@ -16,9 +13,13 @@ import javax.persistence.Transient;
import javax.script.ScriptEngine; import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager; import javax.script.ScriptEngineManager;
import javax.script.ScriptException; import javax.script.ScriptException;
import java.util.LinkedHashMap;
import java.util.Map; import org.hibernate.Session;
import java.util.stream.Collectors; import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.bytecode.enhancement.AbstractEnhancerTestTask;
import org.junit.Assert;
/** /**
* @author Luis Barreiro * @author Luis Barreiro
@ -41,52 +42,73 @@ public class MixedAccessTestTask extends AbstractEnhancerTestTask {
Session s = getFactory().openSession(); Session s = getFactory().openSession();
s.beginTransaction(); s.beginTransaction();
TestEntity testEntity = new TestEntity( "foo" ); try {
testEntity.setParamsAsString( "{\"paramName\":\"paramValue\"}" ); TestEntity testEntity = new TestEntity( "foo" );
s.persist( testEntity ); testEntity.setParamsAsString( "{\"paramName\":\"paramValue\"}" );
s.persist( testEntity );
TestOtherEntity testOtherEntity = new TestOtherEntity( "foo" ); TestOtherEntity testOtherEntity = new TestOtherEntity( "foo" );
testOtherEntity.setParamsAsString( "{\"paramName\":\"paramValue\"}" ); testOtherEntity.setParamsAsString( "{\"paramName\":\"paramValue\"}" );
s.persist( testOtherEntity ); s.persist( testOtherEntity );
s.getTransaction().commit(); s.getTransaction().commit();
s.clear(); }
s.close(); catch ( Exception e ) {
s.getTransaction().rollback();
throw e;
}
finally {
s.close();
}
} }
public void execute() { public void execute() {
Session s = getFactory().openSession(); Session s = getFactory().openSession();
s.beginTransaction(); s.beginTransaction();
TestEntity testEntity = s.get( TestEntity.class, "foo" ); try {
Assert.assertEquals( "{\"paramName\":\"paramValue\"}", testEntity.getParamsAsString() ); TestEntity testEntity = s.get( TestEntity.class, "foo" );
Assert.assertEquals( "{\"paramName\":\"paramValue\"}", testEntity.getParamsAsString() );
TestOtherEntity testOtherEntity = s.get( TestOtherEntity.class, "foo" ); TestOtherEntity testOtherEntity = s.get( TestOtherEntity.class, "foo" );
Assert.assertEquals( "{\"paramName\":\"paramValue\"}", testOtherEntity.getParamsAsString() ); Assert.assertEquals( "{\"paramName\":\"paramValue\"}", testOtherEntity.getParamsAsString() );
// Clean parameters // Clean parameters
cleanup = true; cleanup = true;
testEntity.setParamsAsString( "{}" ); testEntity.setParamsAsString( "{}" );
testOtherEntity.setParamsAsString( "{}" ); testOtherEntity.setParamsAsString( "{}" );
s.getTransaction().commit(); s.getTransaction().commit();
s.clear(); }
s.close(); catch ( RuntimeException e ) {
s.getTransaction().rollback();
throw e;
}
finally {
s.close();
}
} }
protected void cleanup() { protected void cleanup() {
Session s = getFactory().openSession(); Session s = getFactory().openSession();
s.beginTransaction(); s.beginTransaction();
TestEntity testEntity = s.get( TestEntity.class, "foo" ); try {
Assert.assertTrue( testEntity.getParams().isEmpty() ); TestEntity testEntity = s.get( TestEntity.class, "foo" );
Assert.assertTrue( testEntity.getParams().isEmpty() );
TestOtherEntity testOtherEntity = s.get( TestOtherEntity.class, "foo" ); TestOtherEntity testOtherEntity = s.get( TestOtherEntity.class, "foo" );
Assert.assertTrue( testOtherEntity.getParams().isEmpty() ); Assert.assertTrue( testOtherEntity.getParams().isEmpty() );
s.getTransaction().commit(); s.getTransaction().commit();
s.clear(); }
s.close(); catch ( RuntimeException e ) {
s.getTransaction().rollback();
throw e;
}
finally {
s.close();
}
} }
@Entity @Entity

View File

@ -36,7 +36,7 @@ import org.hibernate.test.util.DdlTransactionIsolatorTestingImpl;
*/ */
@RequiresDialect(H2Dialect.class) @RequiresDialect(H2Dialect.class)
public class SuppliedConnectionTest extends ConnectionManagementTestCase { public class SuppliedConnectionTest extends ConnectionManagementTestCase {
private ConnectionProvider cp = ConnectionProviderBuilder.buildConnectionProvider(); private ConnectionProvider cp;
private Connection connectionUnderTest; private Connection connectionUnderTest;
@BeforeClassOnce @BeforeClassOnce

View File

@ -7,7 +7,10 @@
package org.hibernate.test.entitymode.dom4j; package org.hibernate.test.entitymode.dom4j;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.internal.log.DeprecationLogger; import org.hibernate.internal.log.DeprecationLogger;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.logger.LoggerInspectionRule; import org.hibernate.testing.logger.LoggerInspectionRule;
@ -21,6 +24,7 @@ import org.junit.Test;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class DeprecationLoggingTest extends BaseUnitTestCase { public class DeprecationLoggingTest extends BaseUnitTestCase {
@Rule @Rule
public LoggerInspectionRule logInspection = new LoggerInspectionRule( DeprecationLogger.DEPRECATION_LOGGER ); public LoggerInspectionRule logInspection = new LoggerInspectionRule( DeprecationLogger.DEPRECATION_LOGGER );
@ -28,7 +32,16 @@ public class DeprecationLoggingTest extends BaseUnitTestCase {
public void basicTest() { public void basicTest() {
logInspection.registerListener( LogListenerImpl.INSTANCE ); logInspection.registerListener( LogListenerImpl.INSTANCE );
new MetadataSources().addResource( "org/hibernate/test/entitymode/dom4j/Car.hbm.xml" ) MetadataSources metadataSources = new MetadataSources()
.buildMetadata(); .addResource( "org/hibernate/test/entitymode/dom4j/Car.hbm.xml" );
try {
metadataSources.buildMetadata();
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
} }

View File

@ -12,6 +12,9 @@ import javax.persistence.Id;
import org.hibernate.AnnotationException; import org.hibernate.AnnotationException;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test; import org.junit.Test;
@ -24,14 +27,20 @@ import static org.junit.Assert.fail;
public class InvalidEnumeratedJavaTypeTest extends BaseUnitTestCase { public class InvalidEnumeratedJavaTypeTest extends BaseUnitTestCase {
@Test @Test
public void testInvalidMapping() { public void testInvalidMapping() {
MetadataSources metadataSources = new MetadataSources( )
.addAnnotatedClass( TheEntity.class );
try { try {
new MetadataSources( ) metadataSources.buildMetadata();
.addAnnotatedClass( TheEntity.class )
.buildMetadata();
fail( "Was expecting failure" ); fail( "Was expecting failure" );
} }
catch (AnnotationException ignore) { catch (AnnotationException ignore) {
} }
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Entity @Entity

View File

@ -2,6 +2,7 @@ package org.hibernate.test.hbm.query;
import java.io.StringReader; import java.io.StringReader;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.engine.jdbc.ReaderInputStream; import org.hibernate.engine.jdbc.ReaderInputStream;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
@ -32,7 +33,8 @@ public class NamedQueryTest extends BaseUnitTestCase {
Configuration cfg = new Configuration(); Configuration cfg = new Configuration();
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
cfg.addInputStream(new ReaderInputStream(new StringReader(NAMED_QUERY_HBM_XML))); cfg.addInputStream(new ReaderInputStream(new StringReader(NAMED_QUERY_HBM_XML)));
cfg.buildSessionFactory(); SessionFactory sessionFactory = cfg.buildSessionFactory();
sessionFactory.close();
} }
public class Bar { public class Bar {

View File

@ -4,11 +4,14 @@ import java.io.StringReader;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.engine.jdbc.ReaderInputStream; import org.hibernate.engine.jdbc.ReaderInputStream;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn; import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryRootReturn; import org.hibernate.engine.query.spi.sql.NativeSQLQueryRootReturn;
import org.hibernate.engine.spi.NamedSQLQueryDefinition; import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Assert; import org.junit.Assert;
@ -42,19 +45,27 @@ public class QueryReturnTest extends BaseUnitTestCase {
@Test @Test
public void testQueryReturn() { public void testQueryReturn() {
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder() StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder()
.applySetting("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); .applySetting("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
MetadataSources metadataSources = new MetadataSources(serviceRegistryBuilder.build()); StandardServiceRegistry standardServiceRegistry = serviceRegistryBuilder.build();
metadataSources.addInputStream(new ReaderInputStream(new StringReader(QUERY_RETURN_HBM_XML))); MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
Metadata metadata = metadataSources.buildMetadata(); try {
NamedSQLQueryDefinition myQuery = metadata.getNamedNativeQueryDefinition("myQuery"); metadataSources.addInputStream(new ReaderInputStream(new StringReader(QUERY_RETURN_HBM_XML)));
Assert.assertNotNull(myQuery); Metadata metadata = metadataSources.buildMetadata();
NativeSQLQueryReturn[] myQueryReturns = myQuery.getQueryReturns(); NamedSQLQueryDefinition myQuery = metadata.getNamedNativeQueryDefinition("myQuery");
Assert.assertNotNull(myQueryReturns); Assert.assertNotNull(myQuery);
Assert.assertEquals(1, myQueryReturns.length); NativeSQLQueryReturn[] myQueryReturns = myQuery.getQueryReturns();
Assert.assertTrue(NativeSQLQueryRootReturn.class.isInstance(myQueryReturns[0])); Assert.assertNotNull(myQueryReturns);
NativeSQLQueryRootReturn myQueryRootReturn = (NativeSQLQueryRootReturn)myQueryReturns[0]; Assert.assertEquals(1, myQueryReturns.length);
Assert.assertEquals("e", myQueryRootReturn.getAlias()); Assert.assertTrue(NativeSQLQueryRootReturn.class.isInstance(myQueryReturns[0]));
Assert.assertEquals("org.hibernate.test.hbm.query.QueryReturnTest$Bar", myQueryRootReturn.getReturnEntityName()); NativeSQLQueryRootReturn myQueryRootReturn = (NativeSQLQueryRootReturn)myQueryReturns[0];
Assert.assertEquals("e", myQueryRootReturn.getAlias());
Assert.assertEquals("org.hibernate.test.hbm.query.QueryReturnTest$Bar", myQueryRootReturn.getReturnEntityName());
}
finally {
if ( standardServiceRegistry instanceof StandardServiceRegistryImpl ) {
( (StandardServiceRegistryImpl) standardServiceRegistry ).destroy();
}
}
} }
public class Bar { public class Bar {

View File

@ -6,8 +6,10 @@
*/ */
package org.hibernate.test.hbm.version; package org.hibernate.test.hbm.version;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test; import org.junit.Test;
@ -18,8 +20,17 @@ import org.junit.Test;
public class GeneratedVersionBindingTest extends BaseUnitTestCase { public class GeneratedVersionBindingTest extends BaseUnitTestCase {
@Test @Test
public void testIt() { public void testIt() {
final Metadata metadata = new MetadataSources() MetadataSources metadataSources = new MetadataSources()
.addResource("org/hibernate/test/hbm/version/Mappings.hbm.xml") .addResource("org/hibernate/test/hbm/version/Mappings.hbm.xml");
.buildMetadata();
try {
metadataSources.buildMetadata();
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
} }

View File

@ -29,8 +29,8 @@ import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Table; import org.hibernate.mapping.Table;
import org.hibernate.mapping.ValueVisitor; import org.hibernate.mapping.ValueVisitor;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl; import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -56,7 +56,9 @@ public class ValueVisitorTest extends BaseUnitTestCase {
@Test @Test
public void testProperCallbacks() { public void testProperCallbacks() {
final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources().buildMetadata(); final MetadataImplementor metadata =
(MetadataImplementor) new MetadataSources( serviceRegistry )
.buildMetadata();
final Table tbl = new Table(); final Table tbl = new Table();
final RootClass rootClass = new RootClass( metadataBuildingContext ); final RootClass rootClass = new RootClass( metadataBuildingContext );

View File

@ -42,8 +42,11 @@ import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl; import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column; import org.hibernate.mapping.Column;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType; import org.hibernate.tool.schema.TargetType;
@ -60,50 +63,75 @@ import static org.junit.Assert.assertSame;
* @author Alessandro Polverini * @author Alessandro Polverini
*/ */
public class CollectionJoinTableNamingTest extends BaseUnitTestCase { public class CollectionJoinTableNamingTest extends BaseUnitTestCase {
@Test @Test
@TestForIssue( jiraKey = "HHH-9908" ) @TestForIssue( jiraKey = "HHH-9908" )
public void testCollectionJoinTableNamingBase() { public void testCollectionJoinTableNamingBase() {
// really the same as the JPA compliant tests; here we just pick up the default ImplicitNamingStrategy // really the same as the JPA compliant tests; here we just pick up the default ImplicitNamingStrategy
final MetadataSources metadataSources = new MetadataSources(); final MetadataSources metadataSources = new MetadataSources();
metadataSources.addAnnotatedClass( Input.class ); try {
metadataSources.addAnnotatedClass( Ptx.class ); metadataSources.addAnnotatedClass( Input.class );
metadataSources.addAnnotatedClass( Ptx.class );
final Metadata metadata = metadataSources.getMetadataBuilder() final Metadata metadata = metadataSources.getMetadataBuilder()
.build(); .build();
assertSameTableUsed( metadata ); assertSameTableUsed( metadata );
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-9908" ) @TestForIssue( jiraKey = "HHH-9908" )
public void testCollectionJoinTableNamingLegacyJpaStrategy() { public void testCollectionJoinTableNamingLegacyJpaStrategy() {
final MetadataSources metadataSources = new MetadataSources(); final MetadataSources metadataSources = new MetadataSources();
metadataSources.addAnnotatedClass( Input.class ); try {
metadataSources.addAnnotatedClass( Ptx.class ); metadataSources.addAnnotatedClass( Input.class );
metadataSources.addAnnotatedClass( Ptx.class );
final Metadata metadata = metadataSources.getMetadataBuilder() final Metadata metadata = metadataSources.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ) .applyImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE )
.build(); .build();
assertSameTableUsed( metadata ); assertSameTableUsed( metadata );
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-9908" ) @TestForIssue( jiraKey = "HHH-9908" )
public void testCollectionJoinTableNamingLegacyHbmStrategy() { public void testCollectionJoinTableNamingLegacyHbmStrategy() {
final MetadataSources metadataSources = new MetadataSources(); final MetadataSources metadataSources = new MetadataSources();
metadataSources.addAnnotatedClass( Input.class ); try {
metadataSources.addAnnotatedClass( Ptx.class ); metadataSources.addAnnotatedClass( Input.class );
metadataSources.addAnnotatedClass( Ptx.class );
final Metadata metadata = metadataSources.getMetadataBuilder() final Metadata metadata = metadataSources.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyLegacyHbmImpl.INSTANCE ) .applyImplicitNamingStrategy( ImplicitNamingStrategyLegacyHbmImpl.INSTANCE )
.build(); .build();
Collection inputs1Mapping = metadata.getCollectionBinding( Ptx.class.getName() + ".inputs1" ); Collection inputs1Mapping = metadata.getCollectionBinding( Ptx.class.getName() + ".inputs1" );
assertEquals( "ptx_inputs1", inputs1Mapping.getCollectionTable().getName() ); assertEquals( "ptx_inputs1", inputs1Mapping.getCollectionTable().getName() );
Collection inputs2Mapping = metadata.getCollectionBinding( Ptx.class.getName() + ".inputs2" ); Collection inputs2Mapping = metadata.getCollectionBinding( Ptx.class.getName() + ".inputs2" );
assertEquals( "ptx_inputs2", inputs2Mapping.getCollectionTable().getName() ); assertEquals( "ptx_inputs2", inputs2Mapping.getCollectionTable().getName() );
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
@Test @Test
@ -112,14 +140,22 @@ public class CollectionJoinTableNamingTest extends BaseUnitTestCase {
// Even in 4.3, with JPA compliant naming, Hibernate creates an unusable table... // Even in 4.3, with JPA compliant naming, Hibernate creates an unusable table...
final MetadataSources metadataSources = new MetadataSources(); final MetadataSources metadataSources = new MetadataSources();
metadataSources.addAnnotatedClass( Input.class ); try {
metadataSources.addAnnotatedClass( Ptx.class ); metadataSources.addAnnotatedClass( Input.class );
metadataSources.addAnnotatedClass( Ptx.class );
final Metadata metadata = metadataSources.getMetadataBuilder() final Metadata metadata = metadataSources.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE ) .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
.build(); .build();
assertSameTableUsed( metadata ); assertSameTableUsed( metadata );
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
private void assertSameTableUsed(Metadata metadata) { private void assertSameTableUsed(Metadata metadata) {

View File

@ -9,11 +9,14 @@ package org.hibernate.test.namingstrategy.complete;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column; import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component; import org.hibernate.mapping.Component;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test; import org.junit.Test;
@ -26,23 +29,32 @@ import static org.junit.Assert.assertNotNull;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public abstract class BaseNamingTests extends BaseUnitTestCase { public abstract class BaseNamingTests extends BaseUnitTestCase {
@Test @Test
public void doTest() { public void doTest() {
final MetadataSources metadataSources = new MetadataSources(); final MetadataSources metadataSources = new MetadataSources();
applySources( metadataSources ); try {
applySources( metadataSources );
final Metadata metadata = metadataSources.getMetadataBuilder() final Metadata metadata = metadataSources.getMetadataBuilder()
.applyImplicitNamingStrategy( getImplicitNamingStrategyToUse() ) .applyImplicitNamingStrategy( getImplicitNamingStrategyToUse() )
.build(); .build();
validateCustomer( metadata ); validateCustomer( metadata );
validateOrder( metadata ); validateOrder( metadata );
validateZipCode( metadata ); validateZipCode( metadata );
validateCustomerRegisteredTrademarks( metadata ); validateCustomerRegisteredTrademarks( metadata );
validateCustomerAddresses( metadata ); validateCustomerAddresses( metadata );
validateCustomerOrders( metadata ); validateCustomerOrders( metadata );
validateCustomerIndustries( metadata ); validateCustomerIndustries( metadata );
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
protected abstract void applySources(MetadataSources metadataSources); protected abstract void applySources(MetadataSources metadataSources);

View File

@ -8,6 +8,9 @@ package org.hibernate.test.naturalid.inheritance.spread;
import org.hibernate.AnnotationException; import org.hibernate.AnnotationException;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
@ -23,14 +26,21 @@ public class SpreadNaturalIdTest extends BaseUnitTestCase {
@Test @Test
@SuppressWarnings("EmptyCatchBlock") @SuppressWarnings("EmptyCatchBlock")
public void testSpreadNaturalIdDeclarationGivesMappingException() { public void testSpreadNaturalIdDeclarationGivesMappingException() {
final MetadataSources metadataSources = new MetadataSources()
.addAnnotatedClass( Principal.class )
.addAnnotatedClass( User.class );
try { try {
new MetadataSources()
.addAnnotatedClass( Principal.class ) metadataSources.buildMetadata();
.addAnnotatedClass( User.class )
.buildMetadata();
fail( "Expected binders to throw an exception" ); fail( "Expected binders to throw an exception" );
} }
catch (AnnotationException expected) { catch (AnnotationException expected) {
} }
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
} }

View File

@ -5,7 +5,6 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
@ -14,16 +13,17 @@ import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.Sequence; import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.mapping.Table; import org.hibernate.mapping.Table;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.schema.internal.DefaultSchemaFilter; import org.hibernate.tool.schema.internal.DefaultSchemaFilter;
import org.hibernate.tool.schema.internal.SchemaCreatorImpl; import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.tool.schema.internal.SchemaDropperImpl; import org.hibernate.tool.schema.internal.SchemaDropperImpl;
import org.hibernate.tool.schema.spi.SchemaFilter; import org.hibernate.tool.schema.spi.SchemaFilter;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.DialectChecks; import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature; import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.ServiceRegistryBuilder; import org.hibernate.testing.ServiceRegistryBuilder;
@ -45,7 +45,7 @@ import static org.hibernate.test.schemafilter.RecordingTarget.Category.TABLE_DRO
@RequiresDialectFeature( value = {DialectChecks.SupportSchemaCreation.class}) @RequiresDialectFeature( value = {DialectChecks.SupportSchemaCreation.class})
public class SchemaFilterTest extends BaseUnitTestCase { public class SchemaFilterTest extends BaseUnitTestCase {
private final ServiceRegistry serviceRegistry; private final StandardServiceRegistryImpl serviceRegistry;
private final Metadata metadata; private final Metadata metadata;
public SchemaFilterTest() { public SchemaFilterTest() {
@ -65,6 +65,11 @@ public class SchemaFilterTest extends BaseUnitTestCase {
this.metadata = ms.buildMetadata(); this.metadata = ms.buildMetadata();
} }
@AfterClassOnce
public void shutdown() {
serviceRegistry.destroy();
}
@Test @Test
public void createSchema_unfiltered() { public void createSchema_unfiltered() {
RecordingTarget target = doCreation( new DefaultSchemaFilter() ); RecordingTarget target = doCreation( new DefaultSchemaFilter() );

View File

@ -6,10 +6,6 @@
*/ */
package org.hibernate.test.service; package org.hibernate.test.service;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Properties; import java.util.Properties;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
@ -19,21 +15,25 @@ import org.hibernate.dialect.H2Dialect;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl; import org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator;
import org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess; import org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess;
import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.env.ConnectionProviderBuilder; import org.hibernate.testing.env.ConnectionProviderBuilder;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Test; import org.junit.Test;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@RequiresDialect( H2Dialect.class ) @RequiresDialect( H2Dialect.class )
public class ServiceBootstrappingTest extends BaseUnitTestCase { public class ServiceBootstrappingTest extends BaseUnitTestCase {
@Test @Test
public void testBasicBuild() { public void testBasicBuild() {
// this test requires that SHOW_SQL property isn't passed from the outside (eg. via Gradle) // this test requires that SHOW_SQL property isn't passed from the outside (eg. via Gradle)
@ -43,16 +43,19 @@ public class ServiceBootstrappingTest extends BaseUnitTestCase {
final StandardServiceRegistryImpl serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder() final StandardServiceRegistryImpl serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
.applySettings( ConnectionProviderBuilder.getConnectionProviderProperties() ) .applySettings( ConnectionProviderBuilder.getConnectionProviderProperties() )
.build(); .build();
final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class ); try {
assertTrue( jdbcServices.getDialect() instanceof H2Dialect ); final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
final ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping( assertTrue( jdbcServices.getDialect() instanceof H2Dialect );
ConnectionProviderJdbcConnectionAccess.class, final ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping(
jdbcServices.getBootstrapJdbcConnectionAccess() ConnectionProviderJdbcConnectionAccess.class,
); jdbcServices.getBootstrapJdbcConnectionAccess()
assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProviderImpl.class ) ); );
assertFalse( jdbcServices.getSqlStatementLogger().isLogToStdout() ); assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProviderImpl.class ) );
assertFalse( jdbcServices.getSqlStatementLogger().isLogToStdout() );
serviceRegistry.destroy(); }
finally {
serviceRegistry.destroy();
}
} }
@Test @Test
@ -61,20 +64,23 @@ public class ServiceBootstrappingTest extends BaseUnitTestCase {
props.put( Environment.SHOW_SQL, "true" ); props.put( Environment.SHOW_SQL, "true" );
StandardServiceRegistryImpl serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder() StandardServiceRegistryImpl serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
.applySettings( props ) .applySettings( props )
.build(); .build();
JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class ); try {
JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
assertTrue( jdbcServices.getDialect() instanceof H2Dialect ); assertTrue( jdbcServices.getDialect() instanceof H2Dialect );
final ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping( final ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping(
ConnectionProviderJdbcConnectionAccess.class, ConnectionProviderJdbcConnectionAccess.class,
jdbcServices.getBootstrapJdbcConnectionAccess() jdbcServices.getBootstrapJdbcConnectionAccess()
); );
assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProviderImpl.class ) ); assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProviderImpl.class ) );
assertTrue( jdbcServices.getSqlStatementLogger().isLogToStdout() ); assertTrue( jdbcServices.getSqlStatementLogger().isLogToStdout() );
}
serviceRegistry.destroy(); finally {
serviceRegistry.destroy();
}
} }
@Test @Test
@ -82,31 +88,40 @@ public class ServiceBootstrappingTest extends BaseUnitTestCase {
StandardServiceRegistryImpl serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder() StandardServiceRegistryImpl serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
.applySettings( ConnectionProviderBuilder.getConnectionProviderProperties() ) .applySettings( ConnectionProviderBuilder.getConnectionProviderProperties() )
.build(); .build();
JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
assertTrue( jdbcServices.getDialect() instanceof H2Dialect );
ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping(
ConnectionProviderJdbcConnectionAccess.class,
jdbcServices.getBootstrapJdbcConnectionAccess()
);
assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProviderImpl.class ) );
Properties props = ConnectionProviderBuilder.getConnectionProviderProperties(); Properties props = ConnectionProviderBuilder.getConnectionProviderProperties();
props.setProperty( Environment.DIALECT, H2Dialect.class.getName() ); props.setProperty( Environment.DIALECT, H2Dialect.class.getName() );
serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder() try {
.applySettings( props ) JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
.addService( ConnectionProvider.class, new UserSuppliedConnectionProviderImpl() )
.build();
jdbcServices = serviceRegistry.getService( JdbcServices.class );
assertTrue( jdbcServices.getDialect() instanceof H2Dialect ); assertTrue( jdbcServices.getDialect() instanceof H2Dialect );
connectionAccess = assertTyping( ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping(
ConnectionProviderJdbcConnectionAccess.class, ConnectionProviderJdbcConnectionAccess.class,
jdbcServices.getBootstrapJdbcConnectionAccess() jdbcServices.getBootstrapJdbcConnectionAccess()
); );
assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( UserSuppliedConnectionProviderImpl.class ) ); assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProviderImpl.class ) );
}
finally {
serviceRegistry.destroy();
}
serviceRegistry.destroy(); try {
serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
.applySettings( props )
.addService( ConnectionProvider.class, new UserSuppliedConnectionProviderImpl() )
.build();
JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
assertTrue( jdbcServices.getDialect() instanceof H2Dialect );
ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping(
ConnectionProviderJdbcConnectionAccess.class,
jdbcServices.getBootstrapJdbcConnectionAccess()
);
assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( UserSuppliedConnectionProviderImpl.class ) );
}
finally {
serviceRegistry.destroy();
}
} }
} }

View File

@ -188,6 +188,8 @@ public class IndividuallySchemaValidatorImplTest extends BaseUnitTestCase {
} }
finally { finally {
new SchemaDropperImpl( serviceRegistry ).doDrop( metadata, false, schemaGenerator ); new SchemaDropperImpl( serviceRegistry ).doDrop( metadata, false, schemaGenerator );
serviceRegistry.destroy();
connectionProvider.stop();
} }
} }
@ -241,6 +243,8 @@ public class IndividuallySchemaValidatorImplTest extends BaseUnitTestCase {
} }
finally { finally {
new SchemaDropperImpl( serviceRegistry ).doDrop( metadata, false, schemaGenerator ); new SchemaDropperImpl( serviceRegistry ).doDrop( metadata, false, schemaGenerator );
serviceRegistry.destroy();
connectionProvider.stop();
} }
} }

View File

@ -7,6 +7,9 @@
package org.hibernate.test.util.dtd; package org.hibernate.test.util.dtd;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test; import org.junit.Test;
@ -21,8 +24,17 @@ public class EntityResolverTest extends BaseUnitTestCase {
// <!ENTITY child SYSTEM "classpath://org/hibernate/test/util/dtd/child.xml"> // <!ENTITY child SYSTEM "classpath://org/hibernate/test/util/dtd/child.xml">
// which we are expecting the Hibernate custom entity resolver to be able to resolve // which we are expecting the Hibernate custom entity resolver to be able to resolve
// locally via classpath lookup. // locally via classpath lookup.
new MetadataSources() final MetadataSources metadataSources = new MetadataSources()
.addResource( "org/hibernate/test/util/dtd/Parent.hbm.xml" ) .addResource( "org/hibernate/test/util/dtd/Parent.hbm.xml" );
.buildMetadata();
try {
metadataSources.buildMetadata();
}
finally {
ServiceRegistry metaServiceRegistry = metadataSources.getServiceRegistry();
if(metaServiceRegistry instanceof BootstrapServiceRegistry ) {
BootstrapServiceRegistryBuilder.destroy( metaServiceRegistry );
}
}
} }
} }

View File

@ -20,6 +20,9 @@ import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
@ -47,6 +50,9 @@ public class RefreshUpdatedDataTest extends BaseNonConfigCoreFunctionalTestCase
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected void addSettings(Map settings) { protected void addSettings(Map settings) {
super.addSettings( settings ); super.addSettings( settings );
if ( H2Dialect.class.equals( Dialect.getDialect().getClass() ) ) {
settings.put( Environment.URL, "jdbc:h2:mem:db-mvcc;MVCC=true" );
}
settings.put( AvailableSettings.GENERATE_STATISTICS, "true" ); settings.put( AvailableSettings.GENERATE_STATISTICS, "true" );
} }

View File

@ -13,23 +13,6 @@
<session-factory> <session-factory>
<!-- Database connection settings -->
<!-- <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost/TestDB</property> -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.H2Dialect
</property>
<!-- Enable Hibernate's automatic session context management --> <!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property> <property name="current_session_context_class">thread</property>

View File

@ -112,18 +112,12 @@ public class NoCdiAvailableTest extends BaseUnitTestCase {
"org.hibernate.jpa.test.cdi.NoCdiAvailableTestDelegate" "org.hibernate.jpa.test.cdi.NoCdiAvailableTestDelegate"
); );
Method mainMethod = delegateClass.getMethod( "passingBeanManager" ); Method mainMethod = delegateClass.getMethod( "passingBeanManager" );
EntityManagerFactory entityManagerFactory = null;
try { try {
entityManagerFactory = (EntityManagerFactory) mainMethod.invoke( null ); mainMethod.invoke( null );
fail( "Expecting failure from missing CDI classes" ); fail( "Expecting failure from missing CDI classes" );
} }
catch (InvocationTargetException expected) { catch (InvocationTargetException expected) {
// hard to assert specific exception types due to classloader trickery // hard to assert specific exception types due to classloader trickery
} }
finally {
if (entityManagerFactory != null ) {
entityManagerFactory.close();
}
}
} }
} }

View File

@ -8,6 +8,8 @@ package org.hibernate.jpa.test.cdi;
import java.util.Collections; import java.util.Collections;
import javax.persistence.EntityManagerFactory;
import org.hibernate.jpa.AvailableSettings; import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.test.PersistenceUnitInfoAdapter; import org.hibernate.jpa.test.PersistenceUnitInfoAdapter;
@ -16,8 +18,8 @@ import org.hibernate.jpa.test.PersistenceUnitInfoAdapter;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class NoCdiAvailableTestDelegate { public class NoCdiAvailableTestDelegate {
public static void passingNoBeanManager() { public static EntityManagerFactory passingNoBeanManager() {
new HibernatePersistenceProvider().createContainerEntityManagerFactory( return new HibernatePersistenceProvider().createContainerEntityManagerFactory(
new PersistenceUnitInfoAdapter(), new PersistenceUnitInfoAdapter(),
Collections.emptyMap() Collections.emptyMap()
); );

View File

@ -16,4 +16,5 @@ hibernate.connection.provider_class HikariCPConnectionProvider
hibernate.hikari.poolName testPool hibernate.hikari.poolName testPool
# Purposefully low and simplisitic. # Purposefully low and simplisitic.
hibernate.hikari.maximumPoolSize 2 hibernate.hikari.maximumPoolSize 2
hibernate.hikari.connectionTimeout 1000
hibernate.hikari.idleTimeout 3000 hibernate.hikari.idleTimeout 3000

View File

@ -21,8 +21,6 @@ public class JdbcProperties {
private final String password; private final String password;
private final Integer poolSize;
public JdbcProperties() { public JdbcProperties() {
Properties connectionProperties = new Properties(); Properties connectionProperties = new Properties();
InputStream inputStream = null; InputStream inputStream = null;
@ -34,8 +32,6 @@ public class JdbcProperties {
connectionProperties.load( inputStream ); connectionProperties.load( inputStream );
url = connectionProperties.getProperty( url = connectionProperties.getProperty(
"hibernate.connection.url" ); "hibernate.connection.url" );
poolSize = Integer.valueOf( connectionProperties.getProperty(
"hibernate.connection.pool_size" ) );
user = connectionProperties.getProperty( user = connectionProperties.getProperty(
"hibernate.connection.username" ); "hibernate.connection.username" );
password = connectionProperties.getProperty( password = connectionProperties.getProperty(
@ -68,8 +64,4 @@ public class JdbcProperties {
public String getPassword() { public String getPassword() {
return password; return password;
} }
public Integer getPoolSize() {
return poolSize;
}
} }

View File

@ -47,7 +47,6 @@ public abstract class BaseUnitTestCase {
@AfterClassOnce @AfterClassOnce
public void assertNoLeaks() { public void assertNoLeaks() {
if ( enableConnectionLeakDetection ) { if ( enableConnectionLeakDetection ) {
log.info( "Assert no leaks!" );
connectionLeakUtil.assertNoLeaks(); connectionLeakUtil.assertNoLeaks();
} }
} }