重写mybatis批量更新
时间: 2023-11-21 16:58:04 浏览: 87
根据提供的引用内容,介绍MyBatis实现批量更新的两种方式:
1. 使用foreach标签进行批量更新
```xml
<update id="batchUpdate" parameterType="java.util.List">
update student set name=#{name}, age=#{age} where id=#{id}
<foreach collection="list" item="item" index="index" separator=";">
update student set name=#{item.name}, age=#{item.age} where id=#{item.id}
</foreach>
</update>
```
2. 使用批量执行器进行批量更新
```xml
<update id="batchUpdate" parameterType="java.util.List" statementType="BATCH">
update student set name=#{name}, age=#{age} where id=#{id}
</update>
```
在Java代码中,需要使用SqlSession的batch方法来执行批量更新操作:
```java
List<StudentVo> list = new ArrayList<>();
// 添加要更新的数据到list中
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
for (StudentVo student : list) {
studentMapper.update(student);
}
sqlSession.flushStatements();
sqlSession.commit();
sqlSession.clearCache();
} finally {
sqlSession.close();
}
```
阅读全文