Session 已关闭
当我按如下方式调用session.begin事务方法时:
Session session = this.getCurrentSession();
Transaction tx = session.beginTransaction();
然后我得到以下异常消息
[2021-04-02 15:27:57] com.pms.mall.controller.LuckyClientController.importByExcel(LuckyClientController.java:161)
<ERROR> 程序异常,请稍后再试.
org.hibernate.SessionException: Session is closed!
at org.hibernate.internal.AbstractSessionImpl.errorIfClosed(AbstractSession**加粗样式**Impl.java:132)
at org.hibernate.internal.SessionImpl.setFlushMode(SessionImpl.java:1478)
at org.springframework.orm.hibernate5.HibernateTransactionManager.doCleanupAfterCompletion(HibernateTransactionManager.java:674)
调用getCurrentSession()并不能保证该会话实际上是打开的
解决办法:使用openSession()
Session session = this.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
实例:
//导入
@Override
public void importByExcel(LuckyClientBean bean ,CommonsMultipartFile uplodaFile) throws Exception {
try {
List<LuckyClient> list = new ArrayList<LuckyClient>();
// 根据选择的文件读取流
InputStream inputStream = uplodaFile.getInputStream();
Workbook workbook = null;
Sheet sheet = null;
Row row = null;
int rowCount = 0;
int sheetCount = 0;
// 获取文件后缀名
String fileTxt = uplodaFile.getFileItem().getName().substring(uplodaFile.getFileItem().getName().lastIndexOf(".") + 1);
if ("xls".equals(fileTxt)) {// 2003版
workbook = new HSSFWorkbook(inputStream);
} else if ("xlsx".equals(fileTxt)) {// 2007版
workbook = new XSSFWorkbook(inputStream);
}
if( null != workbook){
//工作表总数
sheetCount = workbook.getNumberOfSheets();
}else{
throw new NumberFormatException("excel文件损坏!");
}
if(sheetCount >0){
//获取工作表
sheet = workbook.getSheetAt(0);
rowCount = sheet.getPhysicalNumberOfRows();//获取行数
for (int i = 1; i < rowCount; i++) {
row = sheet.getRow(i);// 获取列对象
if (row == null) {
continue;
}
LuckyClient detail;
try {
//将新数据添加至表中
detail = getLuckyClientByRow(bean,row);
}catch(Exception e) {
throw new Exception("第" + (row.getRowNum()+1) +"行,格式错误!"+e);
}
if(detail != null){
list.add(detail);
}
}
}
Session session = this.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
int i=0;
for (LuckyClient entity : list) {
session.saveOrUpdate(entity);
if ( i % 100 == 0 ) { //单次批量操作的数目为100
session.flush(); //清理缓存,执行批量插入20条记录的SQL insert语句
session.clear(); //清空缓存中
}
i++;
}
session.flush(); // 清理缓存,执行批量插入20条记录的SQL insert语句
session.clear();
tx.commit();
session.close();
}finally {
if(uplodaFile != null){
uplodaFile.getFileItem().getInputStream().close();
}
}
}