How can MyBatis update data in bulk?
In MyBatis, batch update can be used to update multiple records simultaneously. Here are the steps to perform batch update using MyBatis:
- Create a Mapper interface that defines a method for batch updating data. For example:
public interface UserMapper {
void batchUpdate(List<User> userList);
}
- Write the SQL statements in the corresponding Mapper.xml file, using the foreach tag to loop through and update the data. For example:
<update id="batchUpdate" parameterType="java.util.List">
update user
<set>
<foreach collection="list" item="item" separator=",">
name = #{item.name},
age = #{item.age}
</foreach>
</set>
where id in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item.id}
</foreach>
</update>
- In Java code, call the method of the Mapper interface and pass in the list of data that needs to be updated. For example:
List<User> userList = new ArrayList<>();
User user1 = new User(1, "Alice", 25);
User user2 = new User(2, "Bob", 30);
userList.add(user1);
userList.add(user2);
userMapper.batchUpdate(userList);
By following the above steps, you can use MyBatis to batch update data. In practical applications, you can define Mapper interfaces and SQL statements according to specific business requirements to achieve batch update functionality.