HHH-8405 - Track down tests that leak SessionFactories

This commit is contained in:
Steve Ebersole 2013-08-01 17:08:15 -05:00
parent 580a71331c
commit f4cc86f7ad
9 changed files with 175 additions and 129 deletions

View File

@ -95,6 +95,7 @@ public class MetadataImplTest extends BaseUnitTestCase {
SessionFactory sessionFactory = metadata.buildSessionFactory();
assertNotNull( sessionFactory );
sessionFactory.close();
}
private void assertFetchProfile(MetadataImpl metadata) {

View File

@ -37,6 +37,7 @@ import org.hibernate.internal.util.SerializationHelper;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.type.SerializationException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
@ -65,7 +66,11 @@ public class SessionFactorySerializationTest extends BaseUnitTestCase {
SessionFactory factory2 = (SessionFactory) SerializationHelper.clone( factory );
assertSame( factory, factory2 );
SessionFactoryRegistry.INSTANCE.removeSessionFactory( "some-other-uuid", NAME, false, null );
factory.close();
assertFalse( SessionFactoryRegistry.INSTANCE.hasRegistrations() );
}
@Test
@ -82,17 +87,20 @@ public class SessionFactorySerializationTest extends BaseUnitTestCase {
StringRefAddr refAddr = (StringRefAddr) reference.get( "uuid" );
String uuid = (String) refAddr.getContent();
// deregister under this uuid...
SessionFactoryRegistry.INSTANCE.removeSessionFactory( uuid, NAME, false, null );
SessionFactoryRegistry.INSTANCE.removeSessionFactory( uuid, null, false, null );
// and then register under a different uuid...
SessionFactoryRegistry.INSTANCE.addSessionFactory( "some-other-uuid", NAME, false, factory, null );
SessionFactoryRegistry.INSTANCE.addSessionFactory( "some-other-uuid", null, false, factory, null );
try {
SerializationHelper.clone( factory );
fail( "Expecting an error" );
}
catch ( SerializationException expected ) {
}
SessionFactoryRegistry.INSTANCE.removeSessionFactory( "some-other-uuid", null, false, null );
factory.close();
assertFalse( SessionFactoryRegistry.INSTANCE.hasRegistrations() );
}
}

View File

@ -55,50 +55,56 @@ public class EmbeddableIntegratorTest extends BaseUnitTestCase {
*/
@Test(expected = GenericJDBCException.class)
public void testWithoutIntegrator() {
ServiceRegistry reg = new StandardServiceRegistryBuilder( new BootstrapServiceRegistryImpl() ).build();
SessionFactory sf = new Configuration().addAnnotatedClass( Investor.class )
.setProperty( "hibernate.hbm2ddl.auto", "create-drop" ).buildSessionFactory( reg );
Session sess = sf.openSession();
Investor myInv = getInvestor();
myInv.setId( 1L );
try {
Session sess = sf.openSession();
Investor myInv = getInvestor();
myInv.setId( 1L );
sess.save( myInv );
sess.flush();
sess.clear();
sess.save( myInv );
sess.flush();
sess.clear();
Investor inv = (Investor) sess.get( Investor.class, 1L );
assertEquals( new BigDecimal( "100" ), inv.getInvestments().get( 0 ).getAmount().getAmount() );
Investor inv = (Investor) sess.get( Investor.class, 1L );
assertEquals( new BigDecimal( "100" ), inv.getInvestments().get( 0 ).getAmount().getAmount() );
sess.close();
sf.close();
StandardServiceRegistryBuilder.destroy( reg );
sess.close();
}
finally {
sf.close();
StandardServiceRegistryBuilder.destroy( reg );
}
}
@Test
public void testWithIntegrator() {
StandardServiceRegistry reg = new StandardServiceRegistryBuilder( new BootstrapServiceRegistryBuilder().with(
new InvestorIntegrator() ).build() ).build();
StandardServiceRegistry reg = new StandardServiceRegistryBuilder(
new BootstrapServiceRegistryBuilder().with( new InvestorIntegrator() ).build()
).build();
SessionFactory sf = new Configuration().addAnnotatedClass( Investor.class )
.setProperty( "hibernate.hbm2ddl.auto", "create-drop" ).buildSessionFactory( reg );
Session sess = sf.openSession();
Investor myInv = getInvestor();
myInv.setId( 2L );
try {
Session sess = sf.openSession();
Investor myInv = getInvestor();
myInv.setId( 2L );
sess.save( myInv );
sess.flush();
sess.clear();
sess.save( myInv );
sess.flush();
sess.clear();
Investor inv = (Investor) sess.get( Investor.class, 2L );
assertEquals( new BigDecimal( "100" ), inv.getInvestments().get( 0 ).getAmount().getAmount() );
Investor inv = (Investor) sess.get( Investor.class, 2L );
assertEquals( new BigDecimal( "100" ), inv.getInvestments().get( 0 ).getAmount().getAmount() );
sess.close();
sf.close();
StandardServiceRegistryBuilder.destroy( reg );
sess.close();
}
finally {
sf.close();
StandardServiceRegistryBuilder.destroy( reg );
}
}
private Investor getInvestor() {

View File

@ -70,6 +70,9 @@ public class OrmVersion1SupportedTest extends BaseCoreFunctionalTestCase {
s.close();
assertEquals( "HHH00196 should not be called", 0, BytemanHelper.getAndResetInvocationCount() );
// which means we also need to close it manually
releaseSessionFactory();
}
@Override

View File

@ -23,7 +23,6 @@
*/
package org.hibernate.test.cfg.cache;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
@ -38,7 +37,8 @@ public class CacheConfigurationTest extends BaseUnitTestCase {
@Test
public void testCacheConfiguration() throws Exception {
// we only care if the SF builds successfully.
Configuration cfg = new Configuration().configure(CFG_XML);
SessionFactory sessionFactory = cfg.buildSessionFactory();
cfg.buildSessionFactory().close();
}
}

View File

@ -24,26 +24,20 @@
package org.hibernate.test.criterion;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.IrrelevantEntity;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LikeExpression;
import org.hibernate.criterion.Restrictions;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.loader.criteria.CriteriaQueryTranslator;
import org.hibernate.type.Type;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
@ -51,7 +45,7 @@ import static org.junit.Assert.assertEquals;
/**
* @author Steve Ebersole
*/
public class CriterionTest extends BaseCoreFunctionalTestCase {
public class CriterionTest extends BaseUnitTestCase {
@Test
public void testIlikeRendering() {
SessionFactory sf = new Configuration()
@ -59,16 +53,21 @@ public class CriterionTest extends BaseCoreFunctionalTestCase {
.setProperty( AvailableSettings.DIALECT, IlikeSupportingDialect.class.getName() )
.setProperty( Environment.HBM2DDL_AUTO, "create-drop" )
.buildSessionFactory();
final Criteria criteria = sf.openSession().createCriteria( IrrelevantEntity.class );
final CriteriaQueryTranslator translator = new CriteriaQueryTranslator(
(SessionFactoryImplementor) sf,
(CriteriaImpl) criteria,
IrrelevantEntity.class.getName(),
"a"
);
final Criterion ilikeExpression = Restrictions.ilike( "name", "abc" );
final String ilikeExpressionSqlFragment = ilikeExpression.toSqlString( criteria, translator );
assertEquals( "a.name insensitiveLike ?", ilikeExpressionSqlFragment );
try {
final Criteria criteria = sf.openSession().createCriteria( IrrelevantEntity.class );
final CriteriaQueryTranslator translator = new CriteriaQueryTranslator(
(SessionFactoryImplementor) sf,
(CriteriaImpl) criteria,
IrrelevantEntity.class.getName(),
"a"
);
final Criterion ilikeExpression = Restrictions.ilike( "name", "abc" );
final String ilikeExpressionSqlFragment = ilikeExpression.toSqlString( criteria, translator );
assertEquals( "a.name insensitiveLike ?", ilikeExpressionSqlFragment );
}
finally {
sf.close();
}
}
@Test
@ -78,16 +77,21 @@ public class CriterionTest extends BaseCoreFunctionalTestCase {
.setProperty( AvailableSettings.DIALECT, NonIlikeSupportingDialect.class.getName() )
.setProperty( Environment.HBM2DDL_AUTO, "create-drop" )
.buildSessionFactory();
final Criteria criteria = sf.openSession().createCriteria( IrrelevantEntity.class );
final CriteriaQueryTranslator translator = new CriteriaQueryTranslator(
(SessionFactoryImplementor) sf,
(CriteriaImpl) criteria,
IrrelevantEntity.class.getName(),
"a"
);
final Criterion ilikeExpression = Restrictions.ilike( "name", "abc" );
final String ilikeExpressionSqlFragment = ilikeExpression.toSqlString( criteria, translator );
assertEquals( "lowLowLow(a.name) like ?", ilikeExpressionSqlFragment );
try {
final Criteria criteria = sf.openSession().createCriteria( IrrelevantEntity.class );
final CriteriaQueryTranslator translator = new CriteriaQueryTranslator(
(SessionFactoryImplementor) sf,
(CriteriaImpl) criteria,
IrrelevantEntity.class.getName(),
"a"
);
final Criterion ilikeExpression = Restrictions.ilike( "name", "abc" );
final String ilikeExpressionSqlFragment = ilikeExpression.toSqlString( criteria, translator );
assertEquals( "lowLowLow(a.name) like ?", ilikeExpressionSqlFragment );
}
finally {
sf.close();
}
}
public static class IlikeSupportingDialect extends Dialect {

View File

@ -39,6 +39,6 @@ public class AnnotatedFormWithBeanValidationNotNullTest extends BaseUnitTestCase
public void testAnnotatedFormWithBeanValidationNotNull() {
Configuration cfg = new Configuration();
cfg.addAnnotatedClass( AnnotatedMaster.class ).addAnnotatedClass( AnnotatedDetail.class );
cfg.buildSessionFactory();
cfg.buildSessionFactory().close();
}
}

View File

@ -34,12 +34,14 @@ import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.mapping.Collection;
import org.hibernate.stat.QueryStatistics;
import org.hibernate.stat.Statistics;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -50,128 +52,141 @@ import static org.junit.Assert.assertNotNull;
*
* @author Emmanuel Bernard
*/
public class StatsTest extends BaseCoreFunctionalTestCase {
public class StatsTest extends BaseUnitTestCase {
public String[] getMappings() {
return new String[] { "stats/Continent.hbm.xml" };
}
public void configure(Configuration cfg) {
super.configure( cfg );
cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
private Configuration buildBaseConfiguration() {
return new Configuration()
.addResource( "org/hibernate/test/stats/Continent.hbm.xml" )
.setProperty( AvailableSettings.GENERATE_STATISTICS, "true" );
}
@Test
@SuppressWarnings( {"UnusedAssignment"})
public void testCollectionFetchVsLoad() throws Exception {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
SessionFactory sf = buildBaseConfiguration()
.setProperty( AvailableSettings.HBM2DDL_AUTO, "create" )
.buildSessionFactory();
Session s = openSession();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
Continent europe = fillDb(s);
tx.commit();
s.clear();
s.close();
s = sf.openSession();
tx = s.beginTransaction();
assertEquals(0, stats.getCollectionLoadCount() );
assertEquals(0, stats.getCollectionFetchCount() );
assertEquals(0, sf.getStatistics().getCollectionLoadCount() );
assertEquals(0, sf.getStatistics().getCollectionFetchCount() );
Continent europe2 = (Continent) s.get( Continent.class, europe.getId() );
assertEquals("Lazy true: no collection should be loaded", 0, stats.getCollectionLoadCount() );
assertEquals( 0, stats.getCollectionFetchCount() );
assertEquals("Lazy true: no collection should be loaded", 0, sf.getStatistics().getCollectionLoadCount() );
assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
europe2.getCountries().size();
assertEquals( 1, stats.getCollectionLoadCount() );
assertEquals("Explicit fetch of the collection state", 1, stats.getCollectionFetchCount() );
assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
assertEquals("Explicit fetch of the collection state", 1, sf.getStatistics().getCollectionFetchCount() );
tx.commit();
s.close();
s = openSession();
tx = s.beginTransaction();
stats.clear();
europe = fillDb(s);
tx.commit();
s.clear();
tx = s.beginTransaction();
assertEquals( 0, stats.getCollectionLoadCount() );
assertEquals( 0, stats.getCollectionFetchCount() );
europe2 = (Continent) s.createQuery(
"from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId()
).uniqueResult();
assertEquals( 1, stats.getCollectionLoadCount() );
assertEquals( "collection should be loaded in the same query as its parent", 0, stats.getCollectionFetchCount() );
tx.commit();
s.close();
sf.getStatistics().clear();
// open second SessionFactory
Collection coll = configuration().getCollectionMapping(Continent.class.getName() + ".countries");
coll.setFetchMode(FetchMode.JOIN);
coll.setLazy(false);
SessionFactory sf = configuration().buildSessionFactory();
stats = sf.getStatistics();
stats.clear();
stats.setStatisticsEnabled(true);
s = sf.openSession();
tx = s.beginTransaction();
europe = fillDb(s);
tx.commit();
s.clear();
tx = s.beginTransaction();
assertEquals( 0, stats.getCollectionLoadCount() );
assertEquals( 0, stats.getCollectionFetchCount() );
assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
europe2 = (Continent) s.createQuery(
"from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId()
).uniqueResult();
assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
assertEquals( "collection should be loaded in the same query as its parent", 0, sf.getStatistics().getCollectionFetchCount() );
tx.commit();
s.close();
// open a new SF
sf.close();
Configuration cfg = buildBaseConfiguration();
cfg.buildMappings();
Collection coll = cfg.getCollectionMapping(Continent.class.getName() + ".countries");
coll.setFetchMode(FetchMode.JOIN);
coll.setLazy(false);
sf = cfg.buildSessionFactory();
s = sf.openSession();
tx = s.beginTransaction();
europe = fillDb(s);
tx.commit();
s.close();
s = sf.openSession();
tx = s.beginTransaction();
assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
europe2 = (Continent) s.get( Continent.class, europe.getId() );
assertEquals( 1, stats.getCollectionLoadCount() );
assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, stats.getCollectionFetchCount() );
assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, sf.getStatistics().getCollectionFetchCount() );
tx.commit();
s.close();
sf.close();
// open third SessionFactory
coll = configuration().getCollectionMapping(Continent.class.getName() + ".countries");
// open yet another SF
sf.close();
cfg = buildBaseConfiguration();
cfg.buildMappings();
coll = cfg.getCollectionMapping( Continent.class.getName() + ".countries" );
coll.setFetchMode(FetchMode.SELECT);
coll.setLazy(false);
sf = configuration().buildSessionFactory();
stats = sf.getStatistics();
stats.clear();
stats.setStatisticsEnabled(true);
sf = cfg.buildSessionFactory();
s = sf.openSession();
tx = s.beginTransaction();
europe = fillDb(s);
tx.commit();
s.clear();
s.close();
s = sf.openSession();
tx = s.beginTransaction();
assertEquals( 0, stats.getCollectionLoadCount() );
assertEquals( 0, stats.getCollectionFetchCount() );
assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
europe2 = (Continent) s.get( Continent.class, europe.getId() );
assertEquals( 1, stats.getCollectionLoadCount() );
assertEquals( "Should do explicit collection load, not part of the first one", 1, stats.getCollectionFetchCount() );
assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
assertEquals( "Should do explicit collection load, not part of the first one", 1, sf.getStatistics().getCollectionFetchCount() );
for ( Object o : europe2.getCountries() ) {
s.delete( o );
}
cleanDb( s );
tx.commit();
s.close();
sf.close();
}
@Test
public void testQueryStatGathering() {
Statistics stats = sessionFactory().getStatistics();
stats.clear();
SessionFactory sf = buildBaseConfiguration()
.setProperty( AvailableSettings.HBM2DDL_AUTO, "create" )
.buildSessionFactory();
Session s = openSession();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
fillDb(s);
tx.commit();
s.close();
s = openSession();
s = sf.openSession();
tx = s.beginTransaction();
final String continents = "from Continent";
int results = s.createQuery( continents ).list().size();
QueryStatistics continentStats = stats.getQueryStatistics( continents );
QueryStatistics continentStats = sf.getStatistics().getQueryStatistics( continents );
assertNotNull( "stats were null", continentStats );
assertEquals( "unexpected execution count", 1, continentStats.getExecutionCount() );
assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
long maxTime = continentStats.getExecutionMaxTime();
assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
assertEquals( maxTime, sf.getStatistics().getQueryExecutionMaxTime() );
// assertEquals( continents, stats.getQueryExecutionMaxTimeQueryString() );
Iterator itr = s.createQuery( continents ).iterate();
@ -196,44 +211,47 @@ public class StatsTest extends BaseCoreFunctionalTestCase {
// explicitly check that statistics for "split queries" get collected
// under the original query
stats.clear();
s = openSession();
sf.getStatistics().clear();
s = sf.openSession();
tx = s.beginTransaction();
final String localities = "from Locality";
results = s.createQuery( localities ).list().size();
QueryStatistics localityStats = stats.getQueryStatistics( localities );
QueryStatistics localityStats = sf.getStatistics().getQueryStatistics( localities );
assertNotNull( "stats were null", localityStats );
// ...one for each split query
assertEquals( "unexpected execution count", 2, localityStats.getExecutionCount() );
assertEquals( "unexpected row count", results, localityStats.getExecutionRowCount() );
maxTime = localityStats.getExecutionMaxTime();
assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
assertEquals( maxTime, sf.getStatistics().getQueryExecutionMaxTime() );
// assertEquals( localities, stats.getQueryExecutionMaxTimeQueryString() );
tx.commit();
s.close();
assertFalse( s.isOpen() );
// native sql queries
stats.clear();
s = openSession();
sf.getStatistics().clear();
s = sf.openSession();
tx = s.beginTransaction();
final String sql = "select id, name from Country";
results = s.createSQLQuery( sql ).addEntity( Country.class ).list().size();
QueryStatistics sqlStats = stats.getQueryStatistics( sql );
QueryStatistics sqlStats = sf.getStatistics().getQueryStatistics( sql );
assertNotNull( "sql stats were null", sqlStats );
assertEquals( "unexpected execution count", 1, sqlStats.getExecutionCount() );
assertEquals( "unexpected row count", results, sqlStats.getExecutionRowCount() );
maxTime = sqlStats.getExecutionMaxTime();
assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
assertEquals( maxTime, sf.getStatistics().getQueryExecutionMaxTime() );
// assertEquals( sql, stats.getQueryExecutionMaxTimeQueryString() );
tx.commit();
s.close();
s = openSession();
s = sf.openSession();
tx = s.beginTransaction();
cleanDb( s );
tx.commit();
s.close();
sf.close();
}
private Continent fillDb(Session s) {

View File

@ -153,6 +153,12 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
if ( sessionFactory == null ) {
return;
}
try {
sessionFactory.close();
}
catch (Exception ignore) {
}
buildSessionFactory();
}
@ -386,7 +392,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
@AfterClassOnce
@SuppressWarnings( {"UnusedDeclaration"})
private void releaseSessionFactory() {
protected void releaseSessionFactory() {
if ( sessionFactory == null ) {
return;
}