Why cant I close HibernateSessionFactory and reope

2019-03-04 05:30发布

问题:

I'm having a problem with closing Hibernate Session Factory, my application allows the user to recreate the database, so when they want to do that firstly I close the hibernate session factory to free Hibernates grip on the database.

public static void closeFactory()
{
    if(factory != null)
    {
        factory.close();
    }
}

Then I wait a few seconds which seems to help

  Thread.sleep(10000);

Then I recreate the database, (FWIW regular hibernate and Envers - I need to create factory for Envers tables to be created), and close the factory down again.

public static void recreateDatabase()
{
    Configuration config;
    config =
            HibernateUtil.getInitializedConfigurationAndRebuildAuditTables();
    new SchemaExport(config).create(true, true);
    factory = config.buildSessionFactory();
    factory.close();
    factory=null;
}

But then when I test a session with:

public static Session getSession()
{
    if (factory == null)
    {
       createFactory();
    }
    Session hibernateSession = factory.openSession();
    return hibernateSession;
}

and try to use it to access a Hibernate based class (Song.class )it fails complaining

org.hibernate.exception.SQLGrammarException: Table "SONG" not found; SQL statement:

basically it cant see any of the tables.

I can stop this problem by not closing the SessionFactory after recreating the table

public static void recreateDatabase()
{
    Configuration config;
    config =
            HibernateUtil.getInitializedConfigurationAndRebuildAuditTables();
    new SchemaExport(config).create(true, true);
    factory = config.buildSessionFactory();
}

however there are two problems with this

  1. I don't understand why I cant close and session reopen the factory
  2. I was originally looking a this code because I was getting occasional Hibernate problems and I wanted to be able to reset the session factory.

Can anyone explain this to me please ?

Note

Without the

factory = config.buildSessionFactory(); line

in the createDatabase() methodafter tables are created I just get

  .......
    create index IDX_SONG_CHANGES_REPORTID on SongChanges (reportId)

    alter table Song_CoverArt 
        add constraint FKE29AB716436A2867 
        foreign key (Song_recNo) 
        references Song

    alter table Song_CoverArt 
        add constraint FKE29AB716792380A 
        foreign key (coverArts_id) 
        references CoverArt
Sep 10, 2014 2:03:45 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete

whereas with that line I get

..............
 create index IDX_SONG_CHANGES_REPORTID on SongChanges (reportId)

    alter table Song_CoverArt 
        add constraint FKE29AB716436A2867 
        foreign key (Song_recNo) 
        references Song

    alter table Song_CoverArt 
        add constraint FKE29AB716792380A 
        foreign key (coverArts_id) 
        references CoverArt
Sep 10, 2014 2:07:27 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Sep 10, 2014 2:07:27 PM org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator instantiateExplicitConnectionProvider
INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider
Sep 10, 2014 2:07:27 PM org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure
INFO: HHH010002: C3P0 using driver: org.h2.Driver at URL: jdbc:h2:Database/songlayer;FILE_LOCK=SOCKET;MVCC=TRUE;DB_CLOSE_ON_EXIT=FALSE;CACHE_SIZE=50000
Sep 10, 2014 2:07:27 PM org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure
INFO: HHH000046: Connection properties: {user=jaikoz, password=****}
Sep 10, 2014 2:07:27 PM org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider configure
INFO: HHH000006: Autocommit mode: false
Sep 10, 2014 2:07:27 PM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
INFO: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@2faff047 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@8f17d9e0 [ acquireIncrement -> 3, acquireRetryAttempts -> 10, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge15494qjod2z19iq4cc|2925bf5b, idleConnectionTestPeriod -> 3000, initialPoolSize -> 3, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 300, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 100, maxStatements -> 0, maxStatementsPerConnection -> 50, minPoolSize -> 20, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@3f342714 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1hge15494qjod2z19iq4cc|45c7e403, jdbcUrl -> jdbc:h2:Database/songlayer;FILE_LOCK=SOCKET;MVCC=TRUE;DB_CLOSE_ON_EXIT=FALSE;CACHE_SIZE=50000, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1hge15494qjod2z19iq4cc|710f4dc7, numHelperThreads -> 10 ]
Sep 10, 2014 2:07:27 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Sep 10, 2014 2:07:27 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Sep 10, 2014 2:07:27 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Sep 10, 2014 2:07:27 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Sep 10, 2014 2:07:28 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Sep 10, 2014 2:07:28 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table Song_AUD drop constraint FK5F61F486DF74E053
Sep 10, 2014 2:07:28 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Constraint "FK5F61F486DF74E053" not found; SQL statement:
alter table Song_AUD drop constraint FK5F61F486DF74E053 [90057-166]
Sep 10, 2014 2:07:28 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table Song_CoverArt_AUD drop constraint FK19C969E7DF74E053
Sep 10, 2014 2:07:28 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Constraint "FK19C969E7DF74E053" not found; SQL statement:
alter table Song_CoverArt_AUD drop constraint FK19C969E7DF74E053 [90057-166]
Sep 10, 2014 2:07:29 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete

I dont understand why, but it is needed.