【发布时间】: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 中的异常:会话已关闭
那么如何解决这个问题呢?
【问题讨论】: