mirror of https://gitee.com/xiaonuobase/snowy
71 lines
2.6 KiB
Java
71 lines
2.6 KiB
Java
package vip.xiaonuo.common.util;
|
|
|
|
import cn.hutool.core.util.StrUtil;
|
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.util.ObjectUtils;
|
|
import vip.xiaonuo.common.annotation.ListQueryMethod;
|
|
import vip.xiaonuo.common.enums.ListQueryType;
|
|
|
|
import java.lang.reflect.Field;
|
|
import java.lang.reflect.InvocationTargetException;
|
|
import java.lang.reflect.Method;
|
|
|
|
@Slf4j
|
|
public class QueryWrapperHelp {
|
|
|
|
public static void createQueryCondition(QueryWrapper queryWrapper, Object obj) {
|
|
try {
|
|
Method[] methods = obj.getClass().getMethods();
|
|
for (Method method : methods) {
|
|
String name = method.getName();
|
|
if (!name.startsWith("get")) {
|
|
continue;
|
|
}
|
|
Object result = method.invoke(obj, null);
|
|
if (result == null) {
|
|
continue;
|
|
}
|
|
name = name.replace("get", "");
|
|
String fildName = name.substring(0, 1).toLowerCase() + name.substring(1, name.length());
|
|
|
|
Field field = QueryWrapperHelp.getField(obj.getClass(), fildName);
|
|
if (field == null) {
|
|
continue;
|
|
}
|
|
ListQueryMethod listQueryMethod = field.getAnnotation(ListQueryMethod.class);
|
|
if (listQueryMethod == null) {
|
|
continue;
|
|
}
|
|
String colName = StrUtil.toUnderlineCase(name);
|
|
QueryWrapperHelp.setQueryWrapper(queryWrapper, listQueryMethod, colName, result);
|
|
}
|
|
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException exception) {
|
|
log.error(exception.getMessage(), exception);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获得字段
|
|
*
|
|
* @param cls
|
|
* @param fildName
|
|
* @return
|
|
*/
|
|
private static Field getField(Class cls, String fildName) {
|
|
try {
|
|
return cls.getDeclaredField(fildName);
|
|
} catch (NoSuchFieldException e) {
|
|
}
|
|
if(cls.getSuperclass()==null){
|
|
return null;
|
|
}
|
|
return QueryWrapperHelp.getField(cls.getSuperclass(),fildName);
|
|
}
|
|
|
|
private static void setQueryWrapper(QueryWrapper queryWrapper, ListQueryMethod listQueryMethod, String colName, Object value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
|
Method method = queryWrapper.getClass().getMethod(listQueryMethod.value().getCode(), Object.class, Object.class);
|
|
method.invoke(queryWrapper, colName, value);
|
|
}
|
|
}
|