update mybatis 批量更新
时间: 2023-11-24 22:06:59 浏览: 200
使用MyBatis进行批量更新有多种方案,其中一种个人推荐的方案如下:
1.在MyBatis的XML文件中,使用foreach动态标签拼接SQL语句,每一条数据的更新语句对应一条update语句,多条语句最终使用";"号进行拼接。
```xml
<update id="updateBatchById">
<foreach collection="list" item="item" separator=";">
update `t_student` set `name` = #{item.name}, `age` = #{item.age} where id = #{item.id}
</foreach>
</update>
```
其中,`list`是传入的参数列表,`item`是列表中的每个元素,`separator`是分隔符,这里使用";"号进行拼接。
2.在Java代码中,调用上述XML文件中定义的update语句,传入参数列表即可。
```java
List<Student> studentList = new ArrayList<>();
// 添加需要更新的学生信息到studentList中
...
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.updateBatchById(studentList);
sqlSession.commit();
} catch (Exception e) {
sqlSession.rollback();
} finally {
sqlSession.close();
}
```
其中,`StudentMapper`是定义的Mapper接口,`updateBatchById`是XML文件中定义的update语句的id。