给大家分享一个通过实体不用写太多的查询条件去实现数据查询。
方法:定义注解类,通过获取注解的字段类型去赋值查询,如果有些未用处理到字段用 Igorn 排除即可,后续可以自已在增加拓展
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
public class SearchHelper {
private SearchHelper() {
throw new IllegalStateException("Utility class");
}
public static QueryWrapper build(Class> entityClass, QueryBaseSO so) {
QueryWrapper> queryWrapper = new QueryWrapper<>();
Arrays.stream(so.getClass().getDeclaredFields()).forEach(field -> {
if (!field.isAnnotationPresent(Ignore.class)) {
ReflectionUtils.makeAccessible(field);
Optional.ofNullable(ReflectionUtils.getField(field, so))
.ifPresent(value -> andSqls(entityClass, queryWrapper, field, value));
}
});
so.structureQueryOrderBy(queryWrapper, entityClass, so.getSidx());
return queryWrapper;
}
public static QueryWrapper build(Class entityClass, QueryBaseSO so, BiConsumer, LambdaQueryWrapper> fn) {
QueryWrapper queryWrapper = new QueryWrapper<>();
LambdaQueryWrapper query = queryWrapper.lambda();
Arrays.stream(so.getClass().getDeclaredFields()).forEach(field -> {
if (!field.isAnnotationPresent(Ignore.class)) {
ReflectionUtils.makeAccessible(field);
Optional.ofNullable(ReflectionUtils.getField(field, so))
.ifPresent(value -> andSqls(entityClass, queryWrapper, field, value));
}
});
fn.accept(queryWrapper, query);
so.structureQueryOrderBy(queryWrapper, entityClass, so.getSidx());
return queryWrapper;
}
private static void andSqls(Class> entityClass, QueryWrapper> sqls, Field field, Object value) {
Optional eField = Optional.ofNullable(ReflectionUtils.findField(entityClass, field.getName()));
if (eField.isPresent() && eField.get().isAnnotationPresent(Column.class)) {
// TK 框架只需要获取实体属性名 eField.get().getAnnotation(Column.class).name()
String columnName = eField.get().getName();
if (field.isAnnotationPresent(Like.class)) {
andLike(sqls, field, value, columnName);
} else if (field.isAnnotationPresent(Equal.class)) {
andEqual(sqls, field, value, columnName);
} else if (value instanceof String) {
sqls.like(columnName , "%" + value + "%");
} else if (value instanceof List) {
sqls.in(columnName ,value);
} else {
sqls.eq(columnName, value);
}
}
}
private static void andLike(QueryWrapper> sqls, Field field, Object value, String columnName) {
Like like = field.getAnnotation(Like.class);
String left = like.left() ? "%" : "";
String right = like.right() ? "%" : "";
if (like.value()) {
sqls.like(columnName, left + value + right);
} else {
sqls.notLike(columnName, left + value + right);
}
}
private static void andEqual(QueryWrapper> sqls, Field field, Object value, String columnName) {
Equal equal = field.getAnnotation(Equal.class);
if (equal.value()) {
sqls.eq(columnName, value);
} else {
sqls.ne(columnName, value);
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)