mybatis 使用SqlSessionDaoSupport批量插入

 */
public class batch  extends SqlSessionDaoSupport {
 
private static final Logger logger = Logger.getLogger(BaseDao.class);


public SqlSessionFactory getNewuisSqlSessionFactory() {
return newuisSqlSessionFactory;



public void setNewuisSqlSessionFactory(
SqlSessionFactory newuisSqlSessionFactory) {
this.newuisSqlSessionFactory = newuisSqlSessionFactory;
}


private SqlSessionFactory newuisSqlSessionFactory;


@PostConstruct
public void SqlSessionFactory() {
super.setSqlSessionFactory(newuisSqlSessionFactory);
}


/**
* 批量插入

* @param statement
* @param list
* @return
* @throws BusException
*/
public int batchInsert(String statement, List list) throws BusException {
int i = 0;
SqlSession session = null;
try {
session = newuisSqlSessionFactory.openSession(ExecutorType.BATCH,
false);
for (int cnt = list.size(); i < cnt; i++) {
session.insert(statement, list.get(i));
if ((i + 1) % WebConstants.BATCH_DEAL_NUM == 0) {// Constants.BATCH_DEAL_NUM为批量提交的条数
session.flushStatements();
}
}
session.flushStatements();
} catch (Throwable t) {
logger.error("批量操作数据异常", t);
throw new BusException(ResponseStatus.FAILD_RES_CODE, "批量操作数据异常");
} finally {
if (session != null) {
session.close();
}
}
return i;
}


}


使用时有时会遇见异常需要将



设置为false

你可能感兴趣的:(mybatis)