mybatis insert 批量插入
时间: 2023-11-23 20:07:38 浏览: 70
MyBatis批量插入(insert)数据操作
5星 · 资源好评率100%
MyBatis提供了两种方式进行批量插入操作,分别是使用foreach标签和使用BatchExecutor。下面是两种方式的示例代码:
1.使用foreach标签进行批量插入
```xml
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO t_user (id, name, password)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id}, #{item.name}, #{item.password})
</foreach>
</insert>
```
Java代码:
```java
List<User> userList = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
User user = new User();
user.setId("id" + i);
user.setName("name" + i);
user.setPassword("password" + i);
userList.add(user);
}
userMapper.batchInsert(userList);
```
2.使用BatchExecutor进行批量插入
Java代码:
```java
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
try {
for (int i = 0; i < 100000; i++) {
User user = new User();
user.setId("id" + i);
user.setName("name" + i);
user.setPassword("password" + i);
userMapper.insert(user);
}
sqlSession.commit();
} finally {
sqlSession.close();
}
```
阅读全文