注意:本教程使用的数据库脚本、数据模型和环境信息请参考 “MyBatis Plus环境准备” 章节,点击下载示例源码。
本章节将介绍 IService 接口中 remove 方法的用法,remove 方法用来删除数据,定义如下:
// 根据 entity 条件,删除记录 boolean remove(Wrapper<T> queryWrapper); // 根据 ID 删除 boolean removeById(Serializable id); // 根据 columnMap 条件,删除记录 boolean removeByMap(Map<String, Object> columnMap); // 删除(根据ID 批量删除) boolean removeByIds(Collection<? extends Serializable> idList);
参数说明:
queryWrapper:实体包装类 QueryWrapper
id:主键ID
columnMap:表字段 map 对象
idList:主键ID列表
(1)根据 ID 删除数据,代码如下:
package com.hxstrive.mybatis_plus.simple_service.remove;
import com.hxstrive.mybatis_plus.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class Remove1Test {
@Autowired
private UserService userService;
@Test
void contextLoads() {
boolean flag = userService.removeById(9991);
System.out.println("flag=" + flag);
}
}(2)根据多个ID批量删除数据,代码如下:
@Test
void contextLoads() {
List<Integer> ids = Arrays.asList(9000, 9992, 9993);
boolean flag = userService.removeByIds(ids);
System.out.println("flag=" + flag);
}(3)根据 QueryWrapper 查询条件删除数据,代码如下:
@Test
void contextLoads() {
QueryWrapper<UserBean> wrapper = new QueryWrapper<>();
wrapper.eq("name", "name-update");
boolean flag = userService.remove(wrapper);
System.out.println("flag=" + flag);
}(4)根据 Map 条件对象删除数据,代码如下:
@Test
void contextLoads() {
Map<String,Object> conditionMap = new HashMap<>();
conditionMap.put("name", "username-update");
boolean flag = userService.removeByMap(conditionMap);
System.out.println("flag=" + flag);
}