Hibernate中的连接太多了

sti*_*vlo 2 java hibernate jpa-2.0

我正在尝试学习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;
        }

}
Run Code Online (Sandbox Code Playgroud)

然后我写了一个小的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();
                }
        }

}
Run Code Online (Sandbox Code Playgroud)

一段时间后我得到的是:

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

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

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

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

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

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

axt*_*avt 8

问题不在于Session交易,而在于交易SessionFactory.您SessionFactory在每次迭代时创建一个新的,不要关闭它.

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

获取Sessions并使用循环内的事务是正确的.