1

I can't save all rows from my file Excel in database, because i get this error :

Exception in thread "main" org.hibernate.SessionException: Session is closed!

My code :

    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();
    }

Anyone have an idea plz ?

user3693890
  • 203
  • 1
  • 6
  • 15
  • I found à solution, but if there is à better solution, it will be welcome: `for(int i=3;i – user3693890 Jun 25 '15 at 09:31
  • 1
    [This](http://stackoverflow.com/questions/4040761/control-the-hibernate-sessionwhen-to-close-it-manually) post might be helpful. `Session session = factory.getCurrentSession();` gives you a session that is being automatically closed once the transaction is commited (or rolledback). – mmalik Jun 25 '15 at 10:20

2 Answers2

0

You are fulling up your first level cache. Clearing and flushing the cache periodically should be considered when your are doing a bulk insert. Also committing in each iteration slow down the insertion.

You have to do something like this..

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();
Bhargav Kumar R
  • 2,190
  • 3
  • 22
  • 38
0

You need to start a Session with factory.openSession() before you can use the current Session.

Maarten Winkels
  • 2,407
  • 16
  • 15