Search in sources :

Example 26 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project mybatis-plus-samples by baomidou.

the class MySqlInjector method getMethodList.

@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
    List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
    // 增加自定义方法
    methodList.add(new DeleteAll());
    methodList.add(new FindOne());
    /**
     * 以下 3 个为内置选装件
     * 头 2 个支持字段筛选函数
     */
    // 例: 不要指定了 update 填充的字段
    methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
    methodList.add(new AlwaysUpdateSomeColumnById());
    methodList.add(new LogicDeleteByIdWithFill());
    return methodList;
}
Also used : FindOne(com.baomidou.samples.injector.methods.FindOne) List(java.util.List) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) FindOne(com.baomidou.samples.injector.methods.FindOne) InsertBatchSomeColumn(com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn) FieldFill(com.baomidou.mybatisplus.annotation.FieldFill) AbstractMethod(com.baomidou.mybatisplus.core.injector.AbstractMethod) AlwaysUpdateSomeColumnById(com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById) LogicDeleteByIdWithFill(com.baomidou.mybatisplus.extension.injector.methods.LogicDeleteByIdWithFill) DeleteAll(com.baomidou.samples.injector.methods.DeleteAll) DefaultSqlInjector(com.baomidou.mybatisplus.core.injector.DefaultSqlInjector) DeleteAll(com.baomidou.samples.injector.methods.DeleteAll) AbstractMethod(com.baomidou.mybatisplus.core.injector.AbstractMethod) InsertBatchSomeColumn(com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn) LogicDeleteByIdWithFill(com.baomidou.mybatisplus.extension.injector.methods.LogicDeleteByIdWithFill) AlwaysUpdateSomeColumnById(com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById)

Example 27 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project chao-cloud by chaojunzi.

the class DynamicDataSourceInterceptor method getDsName.

private String getDsName(IService<?> service) {
    Class<?> entityClass = service.getEntityClass();
    TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
    String tableName = tableInfo.getTableName();
    if (tableDataSourceMap.containsKey(tableName)) {
        return tableDataSourceMap.get(tableName);
    }
    return properties.getPrimary();
}
Also used : TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo)

Example 28 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project chao-cloud by chaojunzi.

the class MybatisUtil method buildSql.

/**
 * 根据wrapper生成sql 如:a=1 and b=2
 *
 * @param <T>       实体类型
 * @param wrapper   条件
 * @param beanClass bean类型
 * @return sql条件
 */
static <T> String buildSql(LambdaQueryWrapper<T> wrapper, Class<T> beanClass) {
    // 判断bean是否加载
    TableInfo info = FunctionUtil.buildTableInfo(beanClass);
    Assert.notNull(info, "无效的数据实体 beanClass={}", beanClass.getName());
    String targetSql = wrapper.getTargetSql();
    if (StrUtil.isBlank(targetSql)) {
        return null;
    }
    int count = StrUtil.count(targetSql, MybatisConstant.ASK);
    Map<String, Object> valuePairs = wrapper.getParamNameValuePairs();
    Object[] vals = // 
    IntStream.range(1, count + 1).mapToObj(i -> {
        Object obj = valuePairs.get("MPGENVAL" + i);
        if (obj instanceof Date) {
            obj = DateUtil.formatDateTime((Date) obj);
        }
        return obj;
    }).toArray();
    // 去掉首尾括号
    return StrUtil.format(StrUtil.replace(targetSql, MybatisConstant.ASK, "'{}'"), vals);
}
Also used : SFunction(com.baomidou.mybatisplus.core.toolkit.support.SFunction) DateUtil(cn.hutool.core.date.DateUtil) ApplySql(com.chao.cloud.common.extra.mybatis.common.ApplySql) MybatisConstant(com.chao.cloud.common.extra.mybatis.constant.MybatisConstant) Date(java.util.Date) MergeSegments(com.baomidou.mybatisplus.core.conditions.segments.MergeSegments) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) ClassUtil(cn.hutool.core.util.ClassUtil) DbType(com.baomidou.mybatisplus.annotation.DbType) Constants(com.baomidou.mybatisplus.core.toolkit.Constants) SqlKeyword(com.baomidou.mybatisplus.core.enums.SqlKeyword) Wrapper(com.baomidou.mybatisplus.core.conditions.Wrapper) Map(java.util.Map) ApplySqlSegment(com.chao.cloud.common.extra.mybatis.common.ApplySql.ApplySqlSegment) FuncExps(com.chao.cloud.common.extra.mybatis.common.FuncExps) Method(java.lang.reflect.Method) Wrappers(com.baomidou.mybatisplus.core.toolkit.Wrappers) AbstractISegmentList(com.baomidou.mybatisplus.core.conditions.segments.AbstractISegmentList) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ReUtil(cn.hutool.core.util.ReUtil) Collectors(java.util.stream.Collectors) TableInfoHelper(com.baomidou.mybatisplus.core.metadata.TableInfoHelper) List(java.util.List) StrUtil(cn.hutool.core.util.StrUtil) QueryCondition(com.chao.cloud.common.extra.mybatis.annotation.QueryCondition) ReflectUtil(cn.hutool.core.util.ReflectUtil) ArrayUtil(cn.hutool.core.util.ArrayUtil) Optional(java.util.Optional) Convert(cn.hutool.core.convert.Convert) IPage(com.baomidou.mybatisplus.core.metadata.IPage) IntStream(java.util.stream.IntStream) ParamValue(com.chao.cloud.common.extra.mybatis.common.ApplySql.ParamValue) IService(com.baomidou.mybatisplus.extension.service.IService) ArrayList(java.util.ArrayList) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) WeakReference(java.lang.ref.WeakReference) SerializedLambda(com.baomidou.mybatisplus.core.toolkit.support.SerializedLambda) SqlTemplate(com.chao.cloud.common.extra.mybatis.common.SqlTemplate) AnnotationUtil(cn.hutool.core.annotation.AnnotationUtil) Assert(cn.hutool.core.lang.Assert) Field(java.lang.reflect.Field) TableField(com.baomidou.mybatisplus.annotation.TableField) Consumer(java.util.function.Consumer) AbstractWrapper(com.baomidou.mybatisplus.core.conditions.AbstractWrapper) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) CollUtil(cn.hutool.core.collection.CollUtil) ISqlSegment(com.baomidou.mybatisplus.core.conditions.ISqlSegment) TableFieldInfo(com.baomidou.mybatisplus.core.metadata.TableFieldInfo) SpringUtil(cn.hutool.extra.spring.SpringUtil) Collections(java.util.Collections) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) Date(java.util.Date)

Example 29 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo 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;
}
Also used : Method(java.lang.reflect.Method) SqlTemplate(com.chao.cloud.common.extra.mybatis.common.SqlTemplate) Field(java.lang.reflect.Field) TableField(com.baomidou.mybatisplus.annotation.TableField) Collection(java.util.Collection) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) AbstractISegmentList(com.baomidou.mybatisplus.core.conditions.segments.AbstractISegmentList) List(java.util.List) ArrayList(java.util.ArrayList) QueryCondition(com.chao.cloud.common.extra.mybatis.annotation.QueryCondition)

Example 30 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project chao-cloud by chaojunzi.

the class DateTableNameHandler method parseDate.

private List<Date> parseDate(SqlCommandType type, String table, Object parameter) {
    String column = rule.getColumn();
    List<Date> dateList = CollUtil.newArrayList();
    if (type == SqlCommandType.INSERT) {
        // insert默认解析对象
        TableInfo tableInfo = TableInfoHelper.getTableInfo(table);
        if (tableInfo == null) {
            return dateList;
        }
        if (tableInfo.getEntityType() == ClassUtil.getClass(parameter)) {
            List<TableFieldInfo> fieldList = tableInfo.getFieldList();
            TableFieldInfo field = CollUtil.findOne(fieldList, f -> StrUtil.equals(f.getColumn(), column));
            if (field == null) {
                log.warn("[{}]: 分片字段无效 {}", table, column);
                return dateList;
            }
            Object v = BeanUtil.getFieldValue(parameter, field.getProperty());
            dateList.add((Date) v);
            return dateList;
        }
    }
    // 参数解析
    if (parameter instanceof ParamMap) {
        ParamMap paramMap = (ParamMap) parameter;
        Collection values = paramMap.values();
        for (Object val : values) {
            if (val instanceof AbstractWrapper) {
                AbstractWrapper wrapper = (AbstractWrapper) val;
                MergeSegments segments = wrapper.getExpression();
                if (segments == null || segments.getNormal() == null) {
                    continue;
                }
                NormalSegmentList segmentList = segments.getNormal();
                for (int i = 0; i < segmentList.size(); i++) {
                    String dbColumn = segmentList.get(i).getSqlSegment();
                    if (StrUtil.equalsIgnoreCase(dbColumn, column)) {
                        // 匹配到参数
                        i++;
                        ISqlSegment keyword = CollUtil.get(segmentList, i);
                        if (CollUtil.contains(supportSqlKeywords, keyword)) {
                            // 获取到值索引
                            i++;
                            ISqlSegment keySegment = CollUtil.get(segmentList, i);
                            // 索引越界
                            if (keySegment == null) {
                                continue;
                            }
                            // 构造dateList
                            dateList.addAll(getDateByParam(parameter, keySegment));
                            // between ? and ? -> (跳2格)
                            i = i + 2;
                            if (keyword == SqlKeyword.BETWEEN) {
                                keySegment = CollUtil.get(segmentList, i);
                                dateList.addAll(getDateByParam(parameter, keySegment));
                            }
                        }
                    }
                }
                break;
            }
        }
    }
    return dateList;
}
Also used : TableFieldInfo(com.baomidou.mybatisplus.core.metadata.TableFieldInfo) ParamMap(org.apache.ibatis.binding.MapperMethod.ParamMap) AbstractWrapper(com.baomidou.mybatisplus.core.conditions.AbstractWrapper) Date(java.util.Date) MergeSegments(com.baomidou.mybatisplus.core.conditions.segments.MergeSegments) Collection(java.util.Collection) ISqlSegment(com.baomidou.mybatisplus.core.conditions.ISqlSegment) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) NormalSegmentList(com.baomidou.mybatisplus.core.conditions.segments.NormalSegmentList)

Aggregations

TableInfo (com.baomidou.mybatisplus.core.metadata.TableInfo)53 MapperMethod (org.apache.ibatis.binding.MapperMethod)14 Transactional (org.springframework.transaction.annotation.Transactional)13 List (java.util.List)11 Serializable (java.io.Serializable)9 Field (java.lang.reflect.Field)8 TableInfoHelper (com.baomidou.mybatisplus.core.metadata.TableInfoHelper)7 AbstractMethod (com.baomidou.mybatisplus.core.injector.AbstractMethod)6 SqlMethod (com.baomidou.mybatisplus.core.enums.SqlMethod)5 InsertBatchSomeColumn (com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn)5 Collection (java.util.Collection)5 TableFieldInfo (com.baomidou.mybatisplus.core.metadata.TableFieldInfo)4 Constants (com.baomidou.mybatisplus.core.toolkit.Constants)4 ArrayList (java.util.ArrayList)4 Collectors (java.util.stream.Collectors)4 SqlSession (org.apache.ibatis.session.SqlSession)4 CollUtil (cn.hutool.core.collection.CollUtil)3 Convert (cn.hutool.core.convert.Convert)3 ReflectUtil (cn.hutool.core.util.ReflectUtil)3 FieldFill (com.baomidou.mybatisplus.annotation.FieldFill)3