All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.yulichang.wrapper.MPJLambdaWrapper Maven / Gradle / Ivy

There is a newer version: 1.5.2
Show newest version
package com.github.yulichang.wrapper;

import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.config.ConfigProperties;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.toolkit.LambdaUtils;
import com.github.yulichang.toolkit.TableList;
import com.github.yulichang.toolkit.WrapperUtils;
import com.github.yulichang.toolkit.support.ColumnCache;
import com.github.yulichang.wrapper.interfaces.Chain;
import com.github.yulichang.wrapper.interfaces.Query;
import com.github.yulichang.wrapper.interfaces.QueryLabel;
import com.github.yulichang.wrapper.resultmap.Label;
import com.github.yulichang.wrapper.segments.Select;
import com.github.yulichang.wrapper.segments.SelectCache;
import com.github.yulichang.wrapper.segments.SelectNormal;
import com.github.yulichang.wrapper.segments.SelectString;
import lombok.Getter;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 参考 {@link com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper}
 * Lambda 语法使用 Wrapper
 *
 * @author yulichang
 */
@SuppressWarnings({"unused"})
public class MPJLambdaWrapper extends MPJAbstractLambdaWrapper> implements
        Query>, QueryLabel>, Chain {

    /**
     * 查询字段 sql
     */
    private SharedString sqlSelect = new SharedString();
    /**
     * 是否 select distinct
     */
    private boolean selectDistinct = false;
    /**
     * 查询的字段
     */
    @Getter
    private final List getSelectColum() {
        return this.selectColumns;
    }

    @Override
    public void addLabel(Label label) {
        this.resultMap = true;
        this.resultMapMybatisLabel.add(label);
    }

    @Override
    public MPJLambdaWrapper getChildren() {
        return typedThis;
    }


    /**
     * 设置查询字段
     *
     * @param columns 字段数组
     * @return children
     */
    @SafeVarargs
    public final  MPJLambdaWrapper select(SFunction... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            Class aClass = LambdaUtils.getEntityClass(columns[0]);
            Map cacheMap = ColumnCache.getMapField(aClass);
            for (SFunction s : columns) {
                SelectCache cache = cacheMap.get(LambdaUtils.getName(s));
                getSelectColum().add(new SelectNormal(cache, index, hasAlias, alias));
            }
        }
        return typedThis;
    }

    /**
     * 子查询
     */
    public  MPJLambdaWrapper selectSub(Class clazz, Consumer> consumer, SFunction alias) {
        return selectSub(clazz, ConfigProperties.subQueryAlias, consumer, alias);
    }

    /**
     * 子查询
     */
    public  MPJLambdaWrapper selectSub(Class clazz, String st, Consumer> consumer, SFunction alias) {
        MPJLambdaWrapper wrapper = new MPJLambdaWrapper(null, clazz, SharedString.emptyString(), paramNameSeq, paramNameValuePairs,
                new MergeSegments(), SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString(),
                new TableList(), null, null, null, null) {
        };
        wrapper.tableList.setAlias(st);
        wrapper.tableList.setRootClass(clazz);
        wrapper.tableList.setParent(this.tableList);
        wrapper.alias = st;
        wrapper.subTableAlias = st;
        consumer.accept(wrapper);
        String sql = WrapperUtils.buildSubSqlByWrapper(clazz, wrapper, alias);
        this.selectColumns.add(new SelectString(sql, hasAlias, this.alias));
        return typedThis;
    }

    /**
     * union
     */
    @SuppressWarnings("UnusedReturnValue")
    public final MPJLambdaWrapper union(MPJLambdaWrapper... wrappers) {
        StringBuilder sb = new StringBuilder();
        for (MPJLambdaWrapper wrapper : wrappers) {
            Class entityClass = wrapper.getEntityClass();
            Assert.notNull(entityClass, "请使用 new MPJLambdaWrapper(主表.class) 或 JoinWrappers.lambda(主表.class) 构造方法");
            sb.append(" UNION ")
                    .append(WrapperUtils.buildUnionSqlByWrapper(entityClass, wrapper));
        }
        if (Objects.isNull(unionSql)) {
            unionSql = SharedString.emptyString();
        }
        unionSql.setStringValue(unionSql.getStringValue() + sb);
        return typedThis;
    }

    /**
     * union all
     */
    @SafeVarargs
    public final  MPJLambdaWrapper unionAll(MPJLambdaWrapper... wrappers) {
        StringBuilder sb = new StringBuilder();
        for (MPJLambdaWrapper wrapper : wrappers) {
            Class entityClass = wrapper.getEntityClass();
            Assert.notNull(entityClass, "请使用 new MPJLambdaWrapper(主表.class) 或 JoinWrappers.lambda(主表.class) 构造方法");
            sb.append(" UNION ALL ")
                    .append(WrapperUtils.buildUnionSqlByWrapper(entityClass, wrapper));
        }
        if (Objects.isNull(unionSql)) {
            unionSql = SharedString.emptyString();
        }
        unionSql.setStringValue(unionSql.getStringValue() + sb);
        return typedThis;
    }

    /**
     * 查询条件 SQL 片段
     */
    @Override
    public String getSqlSelect() {
        if (StringUtils.isBlank(sqlSelect.getStringValue()) && CollectionUtils.isNotEmpty(selectColumns)) {
            String s = selectColumns.stream().map(i -> {
                if (i.isStr()) {
                    return i.getColumn();
                }
                String prefix;
                if (i.isHasTableAlias()) {
                    prefix = i.getTableAlias();
                } else {
                    if (i.isLabel()) {
                        if (i.isHasTableAlias()) {
                            prefix = i.getTableAlias();
                        } else {
                            prefix = tableList.getPrefix(i.getIndex(), i.getClazz(), true);
                        }
                    } else {
                        prefix = tableList.getPrefix(i.getIndex(), i.getClazz(), false);
                    }
                }
                String str = prefix + StringPool.DOT + i.getColumn();
                if (i.isFunc()) {
                    SFunction[] args = i.getArgs();
                    if (Objects.isNull(args) || args.length == 0) {
                        return String.format(i.getFunc().getSql(), str) + Constant.AS + i.getAlias();
                    } else {
                        return String.format(i.getFunc().getSql(), Arrays.stream(args).map(arg -> {
                            Class entityClass = LambdaUtils.getEntityClass(arg);
                            String prefixByClass = tableList.getPrefixByClass(entityClass);
                            Map mapField = ColumnCache.getMapField(entityClass);
                            SelectCache cache = mapField.get(LambdaUtils.getName(arg));
                            return prefixByClass + StringPool.DOT + cache.getColumn();
                        }).toArray()) + Constant.AS + i.getAlias();
                    }
                } else {
                    return i.isHasAlias() ? (str + Constant.AS + i.getAlias()) : str;
                }
            }).collect(Collectors.joining(StringPool.COMMA));
            sqlSelect.setStringValue(s);
        }
        return sqlSelect.getStringValue();
    }

    @Override
    public String getUnionSql() {
        return Optional.ofNullable(unionSql).map(SharedString::getStringValue).orElse(StringPool.EMPTY);
    }

    public boolean getSelectDistinct() {
        return selectDistinct;
    }

    /**
     * 用于生成嵌套 sql
     * 

故 sqlSelect 不向下传递

*/ @Override protected MPJLambdaWrapper instance() { return instance(index, null, null, null); } @Override protected MPJLambdaWrapper instanceEmpty() { return new MPJLambdaWrapper<>(); } @Override protected MPJLambdaWrapper instance(Integer index, String keyWord, Class joinClass, String tableName) { return new MPJLambdaWrapper<>(getEntity(), getEntityClass(), null, paramNameSeq, paramNameValuePairs, new MergeSegments(), SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString(), this.tableList, index, keyWord, joinClass, tableName); } @Override public void clear() { super.clear(); selectDistinct = false; sqlSelect.toNull(); selectColumns.clear(); resultMapMybatisLabel.clear(); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy