gpt4 book ai didi

java - Hibernate 中的连接太多

转载 作者:行者123 更新时间:2023-12-02 07:08:34 24 4
gpt4 key购买 nike

我正在尝试学习 Hibernate,我编写了最简单的 Person 实体,并试图插入其中的 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();
}
}

}

一段时间后我得到的是:

Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections

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

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

Exception in thread "main" org.hibernate.SessionException: Session was already closed

那么如何解决问题呢?

最佳答案

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

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

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

关于java - Hibernate 中的连接太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8193156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com