2011-11-19 104 views
2

我在学习Hibernate,并且编写了最简单的Person Entity,并试图插入其中的2000个。我知道我正在使用不赞成使用的方法,我会尽量弄清楚以后会发生什么。休眠中的连接太多

首先,这里是类人:

@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; 
     } 

} 

然后我写了插入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:会话已经关闭

那么如何解决这个问题?

回答

7

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

通常,每个应用程序只需要SessionFactory的一个实例,以便您应该在循环外部创建它,并在应用程序停止时明确关闭它。

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

+0

太好了,那是问题所在,谢谢。在后见之明后很明显......所以后来我可以把它变成一个Spring单例,或者在我掌握了hibernate之后,你是否建议我学习[Spring Data](http://www.springsource.org/spring-数据)? – stivlo

+0

@stivlo:是的,在Spring应用程序中,典型的做法是将'SessionFactory'创建为一个单独的对象(对于它有一个特殊的'LocalSessionFactoryBean'辅助类)。关于Spring Data,我并不熟悉它。 – axtavt