mybatis从前端传来数据联合主键批量删除
时间: 2023-11-23 21:06:05 浏览: 137
可以通过在Mapper接口中定义一个方法,使用@DeleteProvider注解,实现使用Mybatis动态SQL语句进行批量删除。
具体实现方法如下:
1.在Mapper接口中定义一个方法,使用@DeleteProvider注解,指定动态SQL生成器类。
@Mapper
public interface YourMapper {
@DeleteProvider(type = YourDynamicSqlBuilder.class, method = "batchDelete")
int batchDelete(List<Map<String, Object>> dataList);
}
2.实现动态SQL生成器类YourDynamicSqlBuilder,实现batchDelete方法,生成动态SQL语句。
public class YourDynamicSqlBuilder {
/**
* 批量删除
*
* @param map 参数
* @return sql
*/
public String batchDelete(Map<String, Object> map) {
List<Map<String, Object>> dataList = (List<Map<String, Object>>) map.get("list");
StringBuilder sql = new StringBuilder();
sql.append("DELETE FROM your_table_name WHERE ");
for (Map<String, Object> data : dataList) {
sql.append("(");
boolean flag = false;
for (String key : data.keySet()) {
if (flag) {
sql.append(" AND ");
} else {
flag = true;
}
sql.append(key).append("=").append("#{list.").append(key).append("}");
}
sql.append(")");
sql.append(" OR ");
}
sql.delete(sql.length() - 4, sql.length());
return sql.toString();
}
}
3.在controller层中调用批量删除方法。
@Autowired
private YourMapper yourMapper;
...
@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
@ResponseBody
public String batchDelete(@RequestBody List<Map<String, Object>> dataList) {
int result = yourMapper.batchDelete(dataList);
return result > 0 ? "success" : "fail";
}
注意,此处的dataList为前端传来的参数,其中包含需要删除的数据的联合主键。具体实现根据自己的业务需求进行调整。
阅读全文