MyBatis中如何实现批量添加?
时间: 2024-05-13 18:14:42 浏览: 60
MyBatis中可以使用批量操作来实现批量添加,下面是具体的实现步骤:
1. 在Mapper XML文件中添加批量添加的SQL语句,例如:
```xml
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO user(username, password) VALUES
<foreach collection="list" item="item" separator=",">
(#{item.username}, #{item.password})
</foreach>
</insert>
```
2. 在Mapper接口中添加批量添加的方法,例如:
```java
int batchInsert(List<User> userList);
```
3. 在Java代码中使用SqlSession的`batch`方法执行批量操作,例如:
```java
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = new ArrayList<>();
// 添加需要批量插入的数据到userList中
int count = userMapper.batchInsert(userList);
sqlSession.commit();
sqlSession.close();
```
通过以上的步骤,就可以在MyBatis中实现批量添加的操作了。