MyBatis提供了updateBatch
方法來(lái)實(shí)現(xiàn)批量更新操作。下面是一個(gè)示例:
public interface UserMapper {
void updateBatch(List<User> users);
}
<update id="updateBatch" parameterType="java.util.List">
update user
<set>
<foreach collection="list" item="user" separator=";">
id = #{user.id}, name = #{user.name}
</foreach>
</set>
</update>
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public void updateBatch(List<User> users) {
userMapper.updateBatch(users);
}
}
@RestController
public class UserController {
@Autowired
private UserService userService;
@PutMapping("/users")
public void updateUsers(@RequestBody List<User> users) {
userService.updateBatch(users);
}
}
通過(guò)以上步驟,就可以實(shí)現(xiàn)MyBatis的批量更新操作。在執(zhí)行updateBatch
方法時(shí),MyBatis會(huì)將傳入的List參數(shù)轉(zhuǎn)換成批量更新的SQL語(yǔ)句執(zhí)行。