繁体   English   中英

Hibernate中的连接太多了

[英]Too many connections in Hibernate

我正在尝试学习Hibernate,我编写了最简单的Person Entity,我试图插入2000个。 我知道我正在使用弃用的方法,我将在稍后尝试找出新的方法。

首先,这是类Person:

@Entity
public class Person {

        private int id;
        private String name;

        @Id
        @GeneratedValue(strategy = GenerationType.TABLE, generator = "person")
        @TableGenerator(name = "person", table = "sequences", allocationSize = 1)
        public int getId() {
                return id;
        }

        public void setId(int id) {
                this.id = id;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

}

然后我写了一个小的App类,用循环插入2000个实体:

public class App {

        private static AnnotationConfiguration config;

        public static void insertPerson() {
                SessionFactory factory = config.buildSessionFactory();
                Session session = factory.getCurrentSession();
                session.beginTransaction();
                Person aPerson = new Person();
                aPerson.setName("John");
                session.save(aPerson);
                session.getTransaction().commit();
        }

        public static void main(String[] args) {
                config = new AnnotationConfiguration();
                config.addAnnotatedClass(Person.class);
                config.configure("hibernate.cfg.xml"); //is the default already
                new SchemaExport(config).create(true, true); //print and execute
                for (int i = 0; i < 2000; i++) {
                        insertPerson();
                }
        }

}

一段时间后我得到的是:

线程“main”中的异常org.hibernate.exception.JDBCConnectionException:无法打开连接

引起:com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:连接太多

现在我知道,如果我将事务置于循环之外它可能会起作用,但我的测试是看看执行多个事务时会发生什么。 而且由于每次只有一个开放,它应该工作。

我试图在提交后添加session.close()但是我得到了

线程“main”org.hibernate.SessionException中的异常:Session已经关闭

那么如何解决这个问题呢?

问题不在于Session和事务,而在于SessionFactory 您在每次迭代时创建一个新的SessionFactory ,而不是关闭它。

通常每个应用程序只需要一个SessionFactory实例,因此您应该在循环外创建它,并在应用程序停止时显式关闭它。

获取Session并使用循环内的事务是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM