我无法保存数据库中Excel文件的所有行,因为我收到此错误:
线程中的异常" main" 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();
}
任何人都有想法?
答案 0 :(得分: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();
答案 1 :(得分:0)
您需要先使用factory.openSession()启动会话,然后才能使用当前会话。