2015-06-25 78 views
1

我无法从我的数据库文件,Excel中保存的所有行,因为我得到这个错误:问题与休眠“会话关闭”

在线程异常“主要” org.hibernate.SessionException:会议关闭了!

我的代码:

AnnotationConfiguration conf = new AnnotationConfiguration(); 
    conf.addAnnotatedClass(Etudiant.class); 
    conf.configure("hibernate.cfg.xml"); 

    new SchemaExport(conf).create(true, true); 
    SessionFactory factory = conf.buildSessionFactory(); 
    Session session = factory.getCurrentSession(); 
    for(int i=3;i<tab.length;i++){ 
     session.beginTransaction(); 

     etudiant.setNom(tab[i]); 
     i++; 
     etudiant.setPrenom(tab[i]); 
     i++; 
     etudiant.setAge(tab[i]); 

     session.save(etudiant); 
     session.getTransaction().commit(); 
    } 

人有一个想法PLZ?

+0

我发现了一个解决方案,但是,如果有一个更好的解决方案,这将受到欢迎:'用于(INT I = 3; I user3693890

+1

[This](http://stackoverflow.com/questions/4040761/control-the-hibernate-sessionwhen-to-close-it-manually)post可能会有所帮助。 'Session session = factory.getCurrentSession();'给你一个会话,一旦事务被提交(或回滚)就会自动关闭。 – mmalik

回答

0

你正在填满你的第一级缓存。当您正在进行批量插入时,应该考虑定期清理和刷新缓存。在每次迭代中提交也会减慢插入速度。

你必须做这样的事情..

13.1. Batch inserts 

When making new objects persistent flush() and then clear() the sessionregularly in order to control the size of the first-level cache. 



Session session = sessionFactory.openSession(); 
Transaction tx = session.beginTransaction(); 

for (int i=0; i<100000; i++) { 
Customer customer = new Customer(.....); 
session.save(customer); 
if (i % 20 == 0) { //20, same as the JDBC batch size 
    //flush a batch of inserts and release memory: 
    session.flush(); 
    session.clear(); 
    } 
} 
tx.commit(); 
session.close(); 
+0

当我继续那样,我仍然有相同的错误 – user3693890

+0

你可以添加错误堆栈跟踪 –

0

你需要开始factory.openSession()会话才可以使用当前会话。