springboot,提交的逗号分隔的uuid怎么处理,才能执行批量删除
以下2种方法,提交参数是一样的
都是通过apipost的form-data提交ids参数,值为1-1,2-2,3-3

方法一
@RequestParam String ids这样接收时
提交的是ids "1-1,2-2",ids的值是一个普通的字符串,收到后要把每个uuid都加上单引号,才能交给sql使用
public R delBooks(@RequestParam String ids) {
//接收参数
ids = Tool.splitString(ids);//转换后:"'1-1','2-2','3-3'"
log.debug("\n 批量删除 ids={}",ids);
bookService.deleteBooksByBookIds(ids);
return R.ok();
}
mapper.xml
这里的sql要求的是 book_id in ('1-1','2-2','3-3')的格式,所以要提前把参数处理成这种格式
<!--根据bookId删除指定的多条记录-->
<delete id="deleteBooksByBookIds" parameterType="String" >
delete from lib_book where book_id in (${ids})
</delete>
一个工具方法
/**
* 将逗号分隔的字符串的各段加上单引号
* 在交给sql语句(where uid in (${ids}))前,需要用到此方法转换
* @param str 英文逗号分隔的字符串,如aaa,bbb
* @return 被逗号分隔的各段,都加了英文单引号,如 'aaa','bbb'
* */
public static String splitString1(String str){
StringBuffer sb = new StringBuffer();
String[] temp = str.split(",");
for (int i = 0; i < temp.length; i++) {
if (!"".equals(temp[i]) && temp[i] != null){
sb.append("'" + temp[i] + "',");
}
}
String result = sb.toString();
String tp = result.substring(result.length() - 1, result.length());
if (",".equals(tp)){
return result.substring(0, result.length() - 1);
}
else{
return result;
}
}
方法二
@RequestParam String[] ids这样接收时
@PostMapping("/delete")
@ApiOperation(value = "删除")
public R delBooks(@RequestParam String[] ids) {
//接收并处理参数(@RequestParam String[] ids)
List<String> list = Arrays.asList(ids);//@RequestParam String[] ids
String idsValue = Tool.splitString2(list);//转换后:"'1-1','2-2','3-3'"
//接收并处理参数,以下方法效果一样(@RequestParam String ids)
//idsValue = Tool.splitString(ids);
//log.debug("\n 批量删除 ids={}",ids);//转换后:"'1-1','2-2','3-3'"
bookService.deleteBooksByBookIds(idsValue);
return R.ok();
}
工具类需要使用这个了
/**
* 将List<String>的各子元素加上单引号,并用英文逗号分隔返回字符串
* 在交给sql语句(where uid in (${ids}))前,需要用到此方法转换
* @param list 控制器中使用RequestParam String[] ids接收接收form-data中的ids
* @return '1-1','2-2'
* */
public static String splitString2(List<String> list){
// 遍历列表,为每个字符串添加单引号
List<String> quotedList = new ArrayList<>();
for (String s : list) {
quotedList.add("'" + s + "'");
}
// 使用逗号连接所有字符串
String result = String.join(",", quotedList);
return result;
}

浙公网安备 33010602011771号