一、条件对应符号
条件 | 对应符号 |
---|---|
包含 | like |
不包含 | notLike |
开始以 | likeLeft |
结束以 | likeRight |
介于 | between |
不介于 | notBetween |
在列表 | in |
不在列表 | notIn |
等于 | eq |
不等于 | ne |
小于 | lt |
小于等于 | le |
大于 | gt |
大于等于 | ge |
二、前端传值
字段对应条件 组装为json对象的字符串
key | value |
---|---|
condition | { “name”:”eq”,”age”:”between”,”score”:”in”} |
查询值正常传递
//json格式
{
"name":"xxxx",
"age":"12,15", //介于
"score":"60,65,53" //在列表
}
//表单格式
name:xxxx
age:12,15 //介于
score:60,65,53 //在列表
三、后端处理
使用对象接收 例:UserQuery
@Data
@EqualsAndHashCode(callSuper = true)
public class UserQuery extends Query implements Serializable {
private static final long serialVersionUID = -6966068051596968967L;
/**
* 人员主键
*/
private Long id;
/**
* 人员姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 分数
*/
private Float score;
}
//1、创建查询
QueryWrapper<User> queryWrapper = Wrappers.<User>query();
//2、获取请求头
String condition = request.getHeader("condition");
//3、组装queryWrapper,统一方法packageQuery
packageQuery(queryWrapper,userQuery,condition)
//查询数据库
IPage<User> page = this.page(Condition.getPage(userQuery), queryWrapper);
//packageQuery 逻辑
private void packageQuery(QueryWrapper queryWrapper, Query query, String condition) {
//转换获取字段的条件map
Map<String, Object> conditionMap = new HashMap<>();
if (Func.isNotEmpty(condition)) {
conditionMap = JsonUtil.toMap(condition);
}
//反射获取所有的字段
Map<String, Object> finalConditionMap = conditionMap;
Map<String, Method> methodMap = new HashMap<>();
Method[] methods = QueryWrapper.class.getMethods();
for (Method method : methods) {
methodMap.put(method.getName(), method);
}
ReflectionUtils.doWithLocalFields(query.getClass(), field -> {
//获取字段名
String name = field.getName();
if ("serialVersionUID".equals(name)) {
return;
}
field.setAccessible(true);
Class<?> typeClass = field.getType();
//获取值
Object o = field.get(query);
if (o != null) {
String methodName = (String) finalConditionMap.getOrDefault(name, "eq");
Method method = methodMap.get(methodName);
if (method == null) {
return;
}
try {
if ("in".equals(methodName) || "notIn".equals(methodName)) {
List list = Arrays.asList(((String) o).split(",")).stream().map(t -> Convert.convert(typeClass, t)).collect(Collectors.toList());
method.invoke(queryWrapper, name, list.toArray());
} else if ("between".equals(methodName) || "notBetween".equals(methodName)) {
String[] split = ((String) o).split(",");
method.invoke(queryWrapper, name, split[0], split[1]);
} else {
method.invoke(queryWrapper, name, Convert.convert(typeClass, o));
}
} catch (Exception e) {
throw new ServiceException("参数有误执行query异常",e);
}
}
});
}