[英]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.