Close SessionFactory in Hibernate 4.3

后端 未结 3 1487
灰色年华
灰色年华 2020-12-31 22:20

I\'m upgrading my Hibernate to the latest version. With my old HibernateUtil.java I had no problems but when upgrading it, the SessionFactory doesn\'t seem to c

3条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 22:54

    You're right, there appears to be a bug in Hibernate 4.3.x in which a thread spawned by Hibernate's default connection pool doesn't get cleaned up on shutdown. I filed a bug here (please vote!):

    https://hibernate.atlassian.net/browse/HHH-8896

    Until it's fixed, you have two choices. You can add a method to your HibernateUtil and use it to force the connection pool to clean itself up at the end of your app's execution:

    public static void stopConnectionProvider() {
        final SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory;
        ConnectionProvider connectionProvider = sessionFactoryImplementor.getConnectionProvider();
        if (Stoppable.class.isInstance(connectionProvider)) {
            ((Stoppable) connectionProvider).stop();
        }        
    }
    

    This works, but it's ugly, hacky, uses a deprecated method, etc. The better solution would be to just use a "real" connection pool, like c3p0, which can be enabled just by adding the following properties to your hibernate.cfg.xml:

    1
    100
    10
    10
    10
    100
    

    Note that if you use another connection pool, you should remove this connection pool property which is currently in your config:

    
    1
    

    Edit: to use c3p0 connection pooling you'll also need the hibernate-c3p0 dependency. Maven example for 4.3.0-SNAPSHOT from the Hibernate snapshots repo:

    
      ...
      
        hibernate-snapshots
        http://snapshots.jboss.org/maven2/
      
      ...
    
    
    
     ...
     
       org.hibernate
       hibernate-c3p0
       4.3.0-SNAPSHOT
     
     ...
    
    

提交回复
热议问题