use of com.chao.cloud.common.extra.mybatis.common.SqlTemplate in project chao-cloud by chaojunzi.
the class MybatisUtil method parseQueryCondition.
/**
* 解析 {@link QueryCondition}
*
* @param <T> 数据实体
* @param param 参数
* @param beanClass 实体类型
* @param wrapper 条件构造器
* @return {@link AbstractWrapper}
*/
static <T> AbstractWrapper<T, ?, ?> parseQueryCondition(Object param, Class<T> beanClass, AbstractWrapper<T, ?, ?> wrapper) {
if (param == null) {
return wrapper;
}
Field[] fields = ReflectUtil.getFields(param.getClass());
if (ArrayUtil.isEmpty(fields)) {
return wrapper;
}
// 获取字段名
TableInfo info = TableInfoHelper.getTableInfo(beanClass);
Assert.notNull(info, "无效的数据实体 beanClass={}", beanClass.getName());
Map<String, String> propColumnMap = info.getFieldList().stream().collect(Collectors.toMap(TableFieldInfo::getProperty, TableFieldInfo::getColumn));
for (Field field : fields) {
// 判断model中是否存在 @QueryCondition 注解
QueryCondition q = field.getAnnotation(QueryCondition.class);
if (q == null) {
continue;
}
SqlTemplate template = q.value();
// 实体字段名字
Class<? extends FuncExps> funcClass = q.funcClass();
String fieldName = field.getName();
SFunction<?, ?> func = null;
if (funcClass != FuncExps.class) {
// 调用sfunction
func = getSFunction(funcClass);
String name = FunctionUtil.getFieldName(func);
if (StrUtil.isNotBlank(name)) {
fieldName = name;
}
}
//
String column = propColumnMap.get(fieldName);
//
boolean sqlSegment = template == SqlTemplate.SEGMENT;
boolean isSql = template == SqlTemplate.APPLY_SQL;
if (!sqlSegment && !isSql) {
Assert.notBlank(column, "数据库字段不匹配;paramName={}", field.getName());
}
// 获取属性值
Object v = ReflectUtil.getFieldValue(param, field);
if (v == null) {
continue;
}
// 处理自定义sql
if (isSql) {
parseApplySql(wrapper, v);
continue;
}
// 排序单独处理
if (template == SqlTemplate.ORDER_BY && func != null) {
Assert.state(v instanceof Boolean, "排序请使用 Boolean 类型(B大写)");
// 反射方法
Method method = ReflectUtil.getMethodByName(wrapper.getClass(), template.getTemplate());
ReflectUtil.invoke(wrapper, method, true, v, func);
continue;
}
// 处理in查询-占位符
if (template == SqlTemplate.IN) {
Assert.state(v instanceof Collection, "in 查询 请传入 集合");
// 反射方法
Method method = ReflectUtil.getMethodByName(wrapper.getClass(), template.getTemplate());
ReflectUtil.invoke(wrapper, method, true, func, v);
continue;
}
//
if (sqlSegment) {
// 必须是String类型
if (v instanceof List) {
List<String> strList = (List<String>) v;
strList.forEach(wrapper::apply);
}
if (v instanceof String) {
wrapper.apply(v.toString());
}
} else {
wrapper.apply(template.getApplySql(column), template.formatValue(v));
}
}
return wrapper;
}
Aggregations