【问题标题】:Too many connections in HibernateHibernate 中的连接太多
【发布时间】:2011-11-19 09:38:54
【问题描述】:

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

}

一段时间后我得到的是:

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

原因:com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:连接太多

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

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

线程“主”org.hibernate.SessionException 中的异常:会话已关闭

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

【问题讨论】:

    标签: java hibernate jpa-2.0


    【解决方案1】:

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

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

    获取Sessions 并在循环内处理事务是正确的。

    【讨论】:

    • 太好了,这就是问题所在,谢谢。事后看来很明显......所以以后我可以让它成为一个Spring单例,或者在我掌握了hibernate之后,你建议我学习Spring Data吗?
    • @stivlo:是的,在 Spring 应用程序中,典型的方法是将 SessionFactory 创建为单例(有一个特殊的 LocalSessionFactoryBean 辅助类)。关于Spring Data,我不是很熟悉。
    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 2012-03-02
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 2013-05-09
    • 2018-08-04
    相关资源
    最近更新 更多