mybatis动态批量插入
时间: 2023-11-23 16:07:13 浏览: 98
mybatis批量添加
以下是Mybatis动态批量插入的示例代码:
```java
public void batchInsert(List<User> userList) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
UserDao userDao = sqlSession.getMapper(UserDao.class);
try {
int batchCount = 1000; // 每批commit的个数
int batchLastIndex = batchCount; // 每批最后一个的下标
for (int index = 0; index < userList.size();) {
if (batchLastIndex >= userList.size()) {
batchLastIndex = userList.size();
userDao.batchInsert(userList.subList(index, batchLastIndex));
sqlSession.commit();
break;// 数据插入完毕,退出循环
} else {
userDao.batchInsert(userList.subList(index, batchLastIndex));
sqlSession.commit();
index = batchLastIndex;// 设置下一批下标
batchLastIndex = index + (batchCount - 1);
}
}
} finally {
sqlSession.close();
}
}
```
阅读全文