Controller
@GetMapping("/list")
public Result<IPage<AssetsInventory>> inventoryList(@RequestParam(value = "pageNo", required = true) Integer pageNo,
@RequestParam(value = "pageSize", required = true) Integer pageSize,
@RequestParam(value = "condition", required = false) String condition) {
Result<IPage<AssetsInventory>> result = new Result<>();
// 动态组装queryWrapper
QueryWrapper<AssetsInventory> queryWrapper = QueryWrapperGenerator.parseWhereSql(condition);
// 分页查询
IPage<AssetsInventory> pageList = assetsInventoryService.page(new Page<>(pageNo, pageSize), queryWrapper);
result.success(pageList);
return result;
}
组装queryWrapper工具类
public class QueryWrapperGenerator {
public static QueryWrapper parseWhereSql(String param) {
QueryWrapper queryWrapper = new QueryWrapper();
// 转义前端传来的参数
String condition = URLDecoder.decode(param, StandardCharsets.UTF_8);
if(StrUtil.isNotEmpty(condition)) {
List<ConditionVo> conditionList = JSON.parseArray(condition, ConditionVo.class);
if(CollUtil.isNotEmpty(conditionList)){
for(ConditionVo conditionVo : conditionList){
if(conditionVo.getValue() != null && !"".equals(conditionVo.getValue())) {
// 驼峰转下划线
String column = humpToLine2(conditionVo.getColumn());
switch (conditionVo.getType()) {
default:
case "eq":
queryWrapper.eq(column, conditionVo.getValue());
break;
case "ne":
queryWrapper.ne(column, conditionVo.getValue());
break;
case "like":
queryWrapper.like(column, conditionVo.getValue());
break;
case "leftlike":
queryWrapper.likeLeft(column, conditionVo.getValue());
break;
case "rightlike":
queryWrapper.likeRight(column, conditionVo.getValue());
break;
case "notlike":
queryWrapper.notLike(column, conditionVo.getValue());
break;
case "gt":
queryWrapper.gt(column, conditionVo.getValue());
break;
case "lt":
queryWrapper.lt(column, conditionVo.getValue());
break;
case "ge":
queryWrapper.ge(column, conditionVo.getValue());
break;
case "le":
queryWrapper.le(column, conditionVo.getValue());
break;
}
}
}
}
}
return queryWrapper;
}
/**
* 驼峰转下划线
*/
private static String humpToLine2(String str) {
Pattern humpPattern = Pattern.compile("[A-Z]");
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
}
ConditionVo
@Data
public class ConditionVo implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 数据库字段名
*/
private String column;
/**
* 字段值
*/
private String value;
/**
* 连接类型,如llike,equals,gt,ge,lt,le
*/
private String type;
}
前端参数
let condition = [
{
column: "name",
value: "test",
type: "eq"
}
]
let requestParams = {
pageNo: 1,
pageSize: 10,
// get请求 需要转义
condition: encodeURIComponent(JSON.stringify(condition ))
}