2015-06-25 80 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()會話纔可以使用當前會話。