MyBatis Batch Update: Update Thousands of Records

In MyBatis, you can use batch update operations to update thousands of records. Here is one way to implement it:

  1. Define a method for batch updating in the Mapper interface as shown below:
public interface UserMapper {
    void updateBatch(List<User> userList);
}
  1. Write the SQL statement for batch update in the corresponding Mapper XML file as shown below:
<update id="updateBatch" parameterType="java.util.List">
    update user
    <set>
        <foreach collection="list" item="item" separator="," >
            username = #{item.username},
            password = #{item.password}
        </foreach>
    </set>
    where id in
    <foreach collection="list" item="item" open="(" close=")" separator=",">
        #{item.id}
    </foreach>
</update>
  1. Call the batch update method in the code as shown below:
List<User> userList = new ArrayList<>();
// 添加需要更新的用户数据到userList中

try(SqlSession sqlSession = sqlSessionFactory.openSession()) {
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.updateBatch(userList);
    sqlSession.commit();
} catch (Exception e) {
    e.printStackTrace();
}

By following the steps above, you can achieve batch updating of several thousand data in MyBatis. It is important to adjust the specific SQL statements and parameter settings according to the actual situation.

bannerAds