阅读量:137
MyBatis提供了updateBatch方法来实现批量更新操作。下面是一个示例:
- 首先定义一个Mapper接口,包含批量更新方法:
public interface UserMapper {
void updateBatch(List users) ;
}
- 在Mapper XML文件中编写对应的SQL语句:
<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层调用Mapper接口的批量更新方法:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public void updateBatch(List users) {
userMapper.updateBatch(users);
}
}
- 在Controller层调用Service层方法执行批量更新操作:
@RestController
public class UserController {
@Autowired
private UserService userService;
@PutMapping("/users")
public void updateUsers(@RequestBody List users) {
userService.updateBatch(users);
}
}
通过以上步骤,就可以实现MyBatis的批量更新操作。在执行updateBatch方法时,MyBatis会将传入的List参数转换成批量更新的SQL语句执行。