Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Hibernate 4.3中关闭SessionFactory_Java_Hibernate - Fatal编程技术网

Java 在Hibernate 4.3中关闭SessionFactory

Java 在Hibernate 4.3中关闭SessionFactory,java,hibernate,Java,Hibernate,我正在将Hibernate升级到最新版本。使用我以前的HibernateUtil.java时,我没有遇到任何问题,但升级时,SessionFactory似乎不再关闭 这是我的新HibernateUtil.java类: import org.hibernate.HibernateException; import org.hibernate.cfg.Configuration; import org.hibernate.SessionFactory; import org.hibernate.bo

我正在将Hibernate升级到最新版本。使用我以前的
HibernateUtil.java
时,我没有遇到任何问题,但升级时,SessionFactory似乎不再关闭

这是我的
HibernateUtil.java
类:

import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            Configuration configuration = new Configuration().configure();
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(builder.build());
        } catch (HibernateException ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void closeSessionFactory() {
        sessionFactory.close();
    }
}
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void closeSessionFactory() {
        sessionFactory.close();
    }
}
这是我以前的HibernateUtil.java类:

import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            Configuration configuration = new Configuration().configure();
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(builder.build());
        } catch (HibernateException ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void closeSessionFactory() {
        sessionFactory.close();
    }
}
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void closeSessionFactory() {
        sessionFactory.close();
    }
}
这是我的hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.connection.password">pass</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>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">false</property>
        <property name="format_sql">false</property>
        <property name="use_sql_comments">false</property>


        <!-- Use the thread as the context -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- Use these files for mapping configuration -->
        <mapping resource="test/Person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
主要方法:

public static void main(String args[]) {
    Logger log = Logger.getLogger("org.hibernate");
    log.setLevel(Level.WARNING);

    Helper helper = new Helper();
    List<Person> people = helper.getPeople(1);

    for (int i = 0; i < people.size(); i++) {
        System.out.println("people " + i + ": " + people.get(i).getID());
    }

    HibernateUtil.closeSessionFactory();
}
publicstaticvoidmain(字符串参数[]){
Logger log=Logger.getLogger(“org.hibernate”);
log.setLevel(Level.WARNING);
Helper=newhelper();
List people=helper.getPeople(1);
for(inti=0;i
没错,Hibernate 4.3.x中似乎存在一个bug,其中由Hibernate默认连接池生成的线程在关机时不会被清除。我在这里提交了一个bug(请投票!):

在修复之前,您有两个选择。您可以向HibernateUtil添加一个方法,并使用该方法在应用程序执行结束时强制连接池自行清理:

public static void stopConnectionProvider() {
    final SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory;
    ConnectionProvider connectionProvider = sessionFactoryImplementor.getConnectionProvider();
    if (Stoppable.class.isInstance(connectionProvider)) {
        ((Stoppable) connectionProvider).stop();
    }        
}
这是可行的,但它很难看,很粗糙,使用了不推荐的方法,等等。更好的解决方案是只使用“真实”连接池,如c3p0,只需将以下属性添加到hibernate.cfg.xml即可启用:

<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.min_size">10</property>
<property name="hibernate.c3p0.timeout">100</property>
1
100
10
10
10
100
请注意,如果使用其他连接池,则应删除当前在配置中的此连接池属性:

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

1.
编辑:要使用c3p0连接池,还需要hibernate-c3p0依赖项。Hibernate snapshots repo中4.3.0-SNAPSHOT的Maven示例:

<repositories>
  ...
  <repository>
    <id>hibernate-snapshots</id>
    <url>http://snapshots.jboss.org/maven2/</url>
  </repository>
  ...
</repositories>

<dependencies>
 ...
 <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-c3p0</artifactId>
   <version>4.3.0-SNAPSHOT</version>
 </dependency>
 ...
<dependencies>

...
休眠快照
http://snapshots.jboss.org/maven2/
...
...
org.hibernate
hibernate-c3p0
4.3.0-快照
...

在主应用程序终止时释放serviceRegistry

public class Service {
private SessionFactory factory;
private ServiceRegistry serviceRegistry;

public void initialize() throws Exception{

    Configuration configuration = new Configuration();
    configuration.configure("com/jeecourse/config/hibernate.cfg.xml");

    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();

    factory = configuration.buildSessionFactory(serviceRegistry);

}

public void close() throws Exception{
    if(serviceRegistry!= null) {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
}

在Hibernate版本4.3.5中,这个问题似乎已经解决了

sessionFactory.close();

在我的程序中工作。

当我运行我的
main
方法时,程序从不停止,它只是保持运行,因为仍有会话打开。我像往常一样调用
closeSessionFactory()
,但现在它实际上不会导致程序在执行后停止。发布创建会话的代码。首先关闭正在使用的会话。close()。即使我先关闭会话,也不会停止