Spring JdbcTemplate实现自定义动态sql拼接功能

news2024/11/25 0:53:31

需求描述:

        sql 需要能满足支持动态拼接,包含 查询字段、查询表、关联表、查询条件、关联表的查询条件、排序、分组、去重等

实现步骤:

        1,创建表及导入测试数据

CREATE TABLE YES_DEV.T11 (
	ID BINARY_BIGINT NOT NULL,
	NAME VARCHAR(10),
	XX BINARY_BIGINT,
	CONSTRAINT _PK_SYS_25_63 PRIMARY KEY (ID)
);

CREATE TABLE YES_DEV.T111 (
	ID BINARY_INTEGER NOT NULL,
	NAME NUMBER
);


INSERT INTO YES_DEV.T11 (ID,NAME,XX) VALUES
	 (11,'123',11),
	 (9,'9',9),
	 (8,'8',8),
	 (7,'7',7),
	 (6,'6',6),
	 (5,'5',5),
	 (4,'4',4),
	 (3,'3',3),
	 (2,'2',2),
	 (1,'1',1);

INSERT INTO YES_DEV.T111 (ID,NAME) VALUES
	 (1,123);

        2,创建项目并引入 pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>testMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!-- 父项目信息 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.8</version>
        <relativePath/>
    </parent>
    <properties>
        <maven.compiler.source>15</maven.compiler.source>
        <maven.compiler.target>15</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <!-- 高斯DB驱动 -->
        <dependency>
            <groupId>com.huawei.gauss</groupId>
            <artifactId>com.huawei.gauss.jdbc.ZenithDriver</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1-jre</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

        3,编写 application.properties文件

spring.datasource.url=jdbc:zenith:@xxxx:xxx
spring.datasource.username=xxx
spring.datasource.password=xxxx
spring.datasource.driver-class-name=com.huawei.gauss.jdbc.inner.GaussDriver
mybatis.mapper-locations=classpath:mapper/*.xml

org.apache.springframework.jdbc.core.JdbcTemplate = debug



        4,核心类之 Column

package com.example.dao.sql;

import com.example.utils.SqlUtils;
import lombok.Getter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Getter
public class Column {

    private final String name;

    private final List<String> tableAliases = new ArrayList<>();

    private Column(String name, List<String> tableAliases) {
        this.name = name;
        if (CollectionUtils.isNotEmpty(tableAliases)) {
            this.tableAliases.addAll(tableAliases);
        }
    }

    public static Column of(String name, String... tableAliases) {
        if (ArrayUtils.isNotEmpty(tableAliases)) {
            tableAliases = Arrays.stream(tableAliases).filter(Objects::nonNull).toArray(String[]::new);
        }
        if (ArrayUtils.isEmpty(tableAliases)) {
            String tableAlias = StringUtils.substringBefore(name, ".").trim();
            if (SqlUtils.isValidAlias(tableAlias)) {
                tableAliases = new String[] {tableAlias};
            }
        }
        return new Column(name, ArrayUtils.isEmpty(tableAliases) ? null : Arrays.asList(tableAliases));
    }

    public String getTableAlias() {
        return tableAliases.isEmpty() ? null : tableAliases.get(0);
    }

}

        5,核心类之 Table

package com.example.dao.sql;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.example.utils.SqlUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Table {

    private String joinType;

    private boolean weak;

    private boolean optimizable = true;

    private Map<String, List<?>> parameterTempData;

    private final String name;

    private final String alias;

    private final String physicalName;

    private final List<Condition> joinConditions = new ArrayList<>();

    private final List<PredicateCondition<?>> joinPredicateConditions = new ArrayList<>();

    private final List<Condition> filterConditions = new ArrayList<>();

    private final List<PredicateCondition<?>> filterPredicateConditions = new ArrayList<>();

    private final List<PropertyCondition> filterPropertyConditions = new ArrayList<>();

    private Table(String name, String alias, String physicalName) {
        this.name = name;
        this.alias = alias;
        this.physicalName = physicalName;
    }

    public static Table of(String name, String physicalName) {
        String separator = " ";
        String normalName = name.trim();
        String alias = StringUtils.substringAfterLast(normalName, separator).trim();
        SqlUtils.assertValidAlias(alias);
        if (StringUtils.isEmpty(physicalName)) {
            physicalName = StringUtils.substringBefore(normalName, separator).trim();
        }
        return new Table(name, alias, physicalName);
    }

    public static Table of(String name) {
        return of(name, (String) null);
    }

    public static Table of(String name, Map<String, List<?>> parameterTempData) {
        return of(name, null, parameterTempData);
    }

    public static Table of(String name, String physicalName, Map<String, List<?>> parameterTempData) {
        Table table = Table.of(name, physicalName);
        table.setParameterTempData(parameterTempData);
        return table;
    }

    public String getJoinType() {
        return joinType;
    }

    public void setJoinType(String joinType) {
        this.joinType = joinType;
    }

    public String getName() {
        return name;
    }

    public String getAlias() {
        return alias;
    }

    public String getPhysicalName() {
        return physicalName;
    }

    public List<Condition> getJoinConditions() {
        return joinConditions;
    }

    public List<PredicateCondition<?>> getJoinPredicateConditions() {
        return joinPredicateConditions;
    }

    public List<Condition> getFilterConditions() {
        return filterConditions;
    }

    public List<PredicateCondition<?>> getFilterPredicateConditions() {
        return filterPredicateConditions;
    }

    public List<PropertyCondition> getFilterPropertyConditions() {
        return filterPropertyConditions;
    }

    public Table on(String condition, String... associationTableAliases) {
        joinConditions.add(Condition.of(condition, associationTableAliases == null ? null : Arrays.asList(associationTableAliases)));
        return this;
    }

    public <T> Table on(PredicateCondition<T> predicateCondition) {
        joinPredicateConditions.add(predicateCondition);
        return this;
    }

    public <T> Table on(Predicate<T> predicate, String condition) {
        return filter(PredicateCondition.of(predicate, condition));
    }

    public <T> Table on(Predicate<T> predicate, Function<T, String> conditionSupplier) {
        return filter(PredicateCondition.of(predicate, conditionSupplier));
    }

    @SafeVarargs
    public final <T> Table on(Predicate<T> predicate, PredicateCondition<T>... predicateConditions) {
        if (ArrayUtils.isEmpty(predicateConditions)) {
            return this;
        }
        for (PredicateCondition<T> predicateCondition : predicateConditions) {
            predicateCondition.setPredicate(predicate.and(predicateCondition.getPredicate()));
            joinPredicateConditions.add(predicateCondition);
        }
        return this;
    }

    public Table filter(String... conditions) {
        if (ArrayUtils.isNotEmpty(conditions)) {
            filterConditions.addAll(Stream.of(conditions).map(Condition::of).collect(Collectors.toList()));
        }
        return this;
    }

    public <T> Table filter(PredicateCondition<T> predicateCondition) {
        filterPredicateConditions.add(predicateCondition);
        return this;
    }

    public <T> Table filter(SFunction<T, Object> fieldGetter, String columnName) {
        return filter(fieldGetter, columnName, true);
    }

    public <T> Table filter(SFunction<T, Object> fieldGetter, String columnName, boolean optimizable) {
        filterPropertyConditions.add(PropertyCondition.of(fieldGetter, columnName, optimizable));
        return this;
    }

    public <T> Table filter(Predicate<T> predicate, String condition) {
        return filter(PredicateCondition.of(predicate, condition));
    }

    public <T> Table filter(Predicate<T> predicate, Function<T, String> conditionSupplier) {
        return filter(PredicateCondition.of(predicate, conditionSupplier));
    }

    @SafeVarargs
    public final <T> Table filter(Predicate<T> predicate, PredicateCondition<T>... predicateConditions) {
        if (ArrayUtils.isEmpty(predicateConditions)) {
            return this;
        }
        for (PredicateCondition<T> predicateCondition : predicateConditions) {
            predicateCondition.setPredicate(predicate.and(predicateCondition.getPredicate()));
            filter(predicateCondition);
        }
        return this;
    }

    public Table weak() {
        return weak(true);
    }

    public Table weak(boolean weak) {
        this.weak = weak;
        return this;
    }

    public boolean isWeak() {
        return weak;
    }

    public Table optimize(boolean optimizable) {
        this.optimizable = optimizable;
        return this;
    }

    public boolean isOptimizable() {
        return optimizable;
    }

    public Map<String, List<?>> getParameterTempData() {
        return parameterTempData;
    }

    public void setParameterTempData(Map<String, List<?>> parameterTempData) {
        this.parameterTempData = parameterTempData;
    }

}

        6,核心类之 Condition

package com.example.dao.sql;

import java.util.Collections;
import java.util.List;

class Condition {

    private final String sql;

    private final List<String> associationTableAliases;

    public static Condition of(String sql) {
        return new Condition(sql, null);
    }

    public static Condition of(String sql, List<String> associationTableAliases) {
        return new Condition(sql, associationTableAliases);
    }

    private Condition(String sql, List<String> associationTableAliases) {
        this.sql = sql;
        this.associationTableAliases = associationTableAliases == null ? Collections.emptyList() : associationTableAliases;
    }

    public String getSql() {
        return sql;
    }

    public List<String> getAssociationTableAliases() {
        return associationTableAliases;
    }

}

        7,核心类之 PredicateCondition

package com.example.dao.sql;

import java.util.function.Function;
import java.util.function.Predicate;

public class PredicateCondition<T> {

    private Predicate<T> predicate;

    private Condition condition;

    private Function<T, Condition> conditionSupplier;

    public static <T> PredicateCondition<T> of(Predicate<T> predicate, String condition) {
        return new PredicateCondition<>(predicate, Condition.of(condition));
    }

    public static <T> PredicateCondition<T> of(Predicate<T> predicate, Function<T, String> conditionSupplier) {
        return new PredicateCondition<>(predicate, parameter -> Condition.of(conditionSupplier.apply(parameter)));
    }

    private PredicateCondition(Predicate<T> predicate, Condition condition) {
        this.predicate = predicate;
        this.condition = condition;
    }

    private PredicateCondition(Predicate<T> predicate, Function<T, Condition> conditionSupplier) {
        this.predicate = predicate;
        this.conditionSupplier = conditionSupplier;
    }

    public Predicate<T> getPredicate() {
        return predicate;
    }

    public void setPredicate(Predicate<T> predicate) {
        this.predicate = predicate;
    }

    public Condition getCondition() {
        return condition;
    }

    public void setCondition(Condition condition) {
        this.condition = condition;
    }

    public Function<T, Condition> getConditionSupplier() {
        return conditionSupplier;
    }

    public void setConditionSupplier(Function<T, Condition> conditionSupplier) {
        this.conditionSupplier = conditionSupplier;
    }

}

        8,核心类之 PropertyCondition

package com.example.dao.sql;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.Data;

@Data
public class PropertyCondition {

    private SFunction<?, Object> fieldGetter;

    private String columnName;

    private boolean optimizable;

    private PropertyCondition(SFunction<?, Object> fieldGetter, String columnName, boolean optimizable) {
        this.fieldGetter = fieldGetter;
        this.columnName = columnName;
        this.optimizable = optimizable;
    }

    public static PropertyCondition of(SFunction<?, Object> fieldGetter, String columnName, boolean optimizable) {
        return new PropertyCondition(fieldGetter, columnName, optimizable);
    }

}

        9,核心类之 SqlBuilder

package com.example.dao.sql;

import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.example.utils.ObjectUtils;
import com.example.utils.SqlUtils;
import com.google.common.base.CaseFormat;
import lombok.Getter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.reflection.property.PropertyNamer;

import java.util.*;
import java.util.stream.Collectors;

//TODO 优化join排序,无依赖的inner join排在前面,有依赖的排在依赖表后面
public class SqlBuilder {

    private static final int PARAM_VALUE_NUM = 1000;

    private static final String NA = "NA";

    private static final String FROM = "FROM";

    private static final String INNER = "INNER";

    private static final String LEFT = "LEFT";

    private static final String RIGHT = "RIGHT";

    private static final String FULL = "FULL";

    @Getter
    private final List<Table> fromTables = new ArrayList<>();

    @Getter
    private final List<Table> queryTables = new ArrayList<>();

    @Getter
    private final List<Column> selectColumns = new ArrayList<>();

    private final List<Condition> filterConditions = new ArrayList<>();

    private final List<String> orderByConditions = new ArrayList<>();

    private final List<String> appendSqlSnippets = new ArrayList<>();

    private final Map<Table, TableQueryCondition> tableQueryConditions = new HashMap<>();

    //private final Map<Table, List<Table>> associationTables = new HashMap<>();

    /*   private final List<PredicateCondition<?>> predicateConditions = new ArrayList<>();*/

    private boolean enablePlaceholder = true;

    private boolean enableOrderBy = true;
    /**
     * 增加字段去重
     */
    private boolean enableDistinct;

    public boolean isEnablePlaceholder() {
        return enablePlaceholder;
    }

    public SqlBuilder setEnablePlaceholder(boolean enablePlaceholder) {
        this.enablePlaceholder = enablePlaceholder;
        return this;
    }

    public SqlBuilder enableOrderBy() {
        this.enableOrderBy = true;
        return this;
    }

    public SqlBuilder disableOrderBy() {
        this.enableOrderBy = false;
        return this;
    }

    public boolean isEnableDistinct() {
        return enableDistinct;
    }

    public void setEnableDistinct(boolean enableDistinct) {
        this.enableDistinct = enableDistinct;
    }

    private static class TableQueryCondition {

        private final Table table;

        private String joinCondition;

        private String filterCondition;

        private boolean referenced;

        public TableQueryCondition(Table table) {
            this.table = table;
        }

        public Table getTable() {
            return table;
        }

        public String getJoinCondition() {
            return joinCondition;
        }

        public void setJoinCondition(String joinCondition) {
            this.joinCondition = joinCondition;
        }

        public String getFilterCondition() {
            return filterCondition;
        }

        public void setFilterCondition(String filterCondition) {
            this.filterCondition = filterCondition;
        }

        public boolean isReferenced() {
            return referenced;
        }

        public void setReferenced(boolean referenced) {
            this.referenced = referenced;
        }

    }

    private Map<String, List<?>> supplementPropertyFilters(Table table, Object queryCriteria) {
        Map<String, List<?>> parameterTempData = new HashMap<>();
        if(queryCriteria == null){
            return parameterTempData;
        }
        for (PropertyCondition propertyCondition : table.getFilterPropertyConditions()) {
            SFunction<?, Object> fieldGetter = propertyCondition.getFieldGetter();
            String fieldName = PropertyNamer.methodToProperty(LambdaUtils.resolve(fieldGetter).getImplMethodName());
            Object fieldValue = fieldGetter.apply(ObjectUtils.cast(queryCriteria));
            if (!(fieldValue instanceof List) || ((List<?>) fieldValue).isEmpty()) {
                continue;
            }
            String columnName = propertyCondition.getColumnName();
            if (!propertyCondition.isOptimizable()) {
                table.optimize(false);
            }
            List<?> collectionValue = ((List<?>) fieldValue);
            if (collectionValue.size() <= PARAM_VALUE_NUM) {
                StringBuilder condition = new StringBuilder(columnName).append(SqlUtils.buildColumnInCondition(fieldName, collectionValue, enablePlaceholder));
                if (collectionValue.contains(NA) || collectionValue.contains(null)) {
                    condition.append(" OR ").append(columnName).append(" is null");
                    table.optimize(false);
                }
                table.filter(condition.toString());
            } else {
                // 当参数值过多采用临时表关联时,将表设置为强关联
                // todo referenced
                table.weak(false);
                String tempTableAlias = "_" + CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fieldName);
                String tempDataType = tempTableAlias.toUpperCase();
                StringBuilder joinCondition = new StringBuilder();
                joinCondition.append(tempTableAlias).append(".value").append(" = ");
                if (collectionValue.contains(NA)) {
                    joinCondition.append("nvl(").append(columnName).append(", '").append(NA).append("')");
                } else {
                    joinCondition.append(columnName);
                }
                Object sampleValue = collectionValue.get(0);
                String queryField = sampleValue instanceof Number ? "to_number(string_value)" : "string_value";
                Table tempTable = Table.of("(SELECT " + queryField + " value FROM t_comm_data_temp WHERE data_type = '" + tempDataType + "') " + tempTableAlias)
                    .on(joinCondition.toString(), table.getAlias());
                tempTable.setJoinType(INNER);
                associationTable(tempTable, table);
                parameterTempData.put(tempDataType, collectionValue);
            }
        }
        return parameterTempData;
    }

    public ExecutionSql builder(Object queryCriteria) {
        ExecutionSql executionSql = new ExecutionSql();
        analyzeTables(queryCriteria, executionSql);
        StringBuilder sql = new StringBuilder();
        appendSelectColumns(sql);
        appendFromTables(sql, executionSql);
        appendJoinTables(sql, executionSql);
        appendWhereConditions(sql);
        appendOrderByConditions(sql);
        appendSqlSnippets(sql);
        executionSql.setSql(sql.toString());
        return executionSql;
    }

    private void analyzeTables(Object queryCriteria, ExecutionSql executionSql) {
        supplementTablePropertyFilters(queryCriteria, executionSql);
        analyzeTableDependences(queryCriteria);
    }

    private void supplementTablePropertyFilters(Object queryCriteria, ExecutionSql executionSql) {
        Map<String, List<?>> parameterTempData = new HashMap<>();
        // Query Table列表需进行拷贝,便于逻辑中动态增加临时表
        for (Table table : new ArrayList<>(queryTables)) {
            parameterTempData.putAll(supplementPropertyFilters(table, queryCriteria));
        }
        executionSql.setParameterTempData(parameterTempData);
    }

    private void analyzeTableDependences(Object queryCriteria) {
        Set<String> referencedTableAliases = filterConditions.stream()
            .flatMap(record -> record.getAssociationTableAliases().stream())
            .collect(Collectors.toSet());
        referencedTableAliases.addAll(selectColumns.stream().flatMap(column -> column.getTableAliases().stream()).collect(Collectors.toSet()));

        Map<String, Table> tableAliasMap = new HashMap<>();
        List<Table> referencedTables = new ArrayList<>();
        for (Table table : queryTables) {
            TableQueryCondition tableAnalysisResult = new TableQueryCondition(table);
            tableAnalysisResult.setJoinCondition(buildConditionSql(table.getJoinConditions(), table.getJoinPredicateConditions(), queryCriteria));
            tableAnalysisResult.setFilterCondition(buildConditionSql(table.getFilterConditions(), table.getFilterPredicateConditions(), queryCriteria));
            // 是否自带过滤条件或被其他其他地方使用
            if (StringUtils.isNotEmpty(tableAnalysisResult.getFilterCondition()) || referencedTableAliases.contains(table.getAlias())) {
                tableAnalysisResult.setReferenced(true);
                referencedTables.add(table);
            }
            // 是否开启优化, 有过滤条件的情况下将Left/Right Join优化成Inner Join,提升查询速度
            if (table.isOptimizable() && Arrays.asList(LEFT, RIGHT).contains(table.getJoinType()) && StringUtils.isNotEmpty(
                tableAnalysisResult.getFilterCondition())) {
                table.setJoinType(INNER);
            }
            tableQueryConditions.put(table, tableAnalysisResult);
            tableAliasMap.put(StringUtils.defaultString(table.getAlias(), table.getName()), table);
        }
        //TODO tale and table 引用依赖
        /*for (Table table : referencedTables) {
            markReferenceTable(table, queryCriteria, tableAliasMap);
        }*/
    }

    /*private void markReferenceTable(Table referencedTable, Object queryCriteria, Map<String, Table> tableAliasMap) {
        List<Condition> effectiveConditions = findEffectiveConditions(referencedTable.getJoinConditions(), referencedTable.getJoinPredicateConditions(),
            queryCriteria);
        effectiveConditions.addAll(
            findEffectiveConditions(referencedTable.getFilterConditions(), referencedTable.getFilterPredicateConditions(), queryCriteria));
        List<String> associationTableAliases = effectiveConditions.stream()
            .flatMap(condition -> condition.getAssociationTableAliases().stream())
            .collect(Collectors.toList());
        for (String associationTableAlias : associationTableAliases) {
            Table associationTable = tableAliasMap.get(associationTableAlias);
            Assert.notNull(associationTable, "Can't find association table for alias [" + associationTableAlias + "]");
            TableQueryCondition tableQueryCondition = tableQueryConditions.get(associationTable);
            if (!tableQueryCondition.isReferenced()) {
                //todo table.setReferenced(true);
                tableQueryCondition.setReferenced(true);
                markReferenceTable(associationTable, queryCriteria, tableAliasMap);
            }
        }
    }*/

    private List<Condition> findEffectiveConditions(List<Condition> conditions, List<PredicateCondition<?>> predicateConditions, Object queryCriteria) {
        List<Condition> effectiveConditions = new ArrayList<>();
        conditions.stream().filter(record -> StringUtils.isNotEmpty(record.getSql())).forEach(effectiveConditions::add);
        if (predicateConditions != null) {
            for (PredicateCondition<?> predicateCondition : predicateConditions) {
                if (predicateCondition.getPredicate().test(ObjectUtils.cast(queryCriteria))) {
                    Condition condition = predicateCondition.getCondition();
                    if (condition != null && StringUtils.isNotEmpty(condition.getSql())) {
                        effectiveConditions.add(condition);
                    }
                    if (predicateCondition.getConditionSupplier() != null) {
                        condition = predicateCondition.getConditionSupplier().apply(ObjectUtils.cast(queryCriteria));
                        if (condition != null && StringUtils.isNotEmpty(condition.getSql())) {
                            effectiveConditions.add(condition);
                        }
                    }
                }
            }
        }
        return effectiveConditions;
    }

    private String buildConditionSql(List<Condition> conditions, List<PredicateCondition<?>> predicateConditions, Object queryCriteria) {
        StringBuilder conditionSql = new StringBuilder();
        List<Condition> effectiveConditions = findEffectiveConditions(conditions, predicateConditions, queryCriteria);
        for (Condition condition : effectiveConditions) {
            appendChildCondition(conditionSql, condition.getSql(), true);
        }
        return conditionSql.toString();
    }

    private void appendSelectColumns(StringBuilder sql) {
        sql.append("SELECT ");
        if(enableDistinct){
            sql.append("DISTINCT ");
        }
        for (int i = 0; i < selectColumns.size(); i++) {
            Column currentColumn = selectColumns.get(i);
            sql.append(currentColumn.getName());
            if (i < selectColumns.size() - 1) {
                sql.append(", ");
            }
        }
    }

    private void appendFromTables(StringBuilder sql, ExecutionSql executionSql) {
        List<Table> fromTables = queryTables.stream().filter(table -> FROM.equals(table.getJoinType())).collect(Collectors.toList());
        sql.append(" FROM ");
        for (int i = 0; i < fromTables.size(); i++) {
            Table table = fromTables.get(i);
            sql.append(table.getName());
            if (i < fromTables.size() - 1) {
                sql.append(", ");
            }
            if (table.getParameterTempData() != null) {
                executionSql.getParameterTempData().putAll(table.getParameterTempData());
            }
        }
    }

    private void appendJoinTables(StringBuilder sql, ExecutionSql executionSql) {
        List<Table> joinTables = queryTables.stream().filter(table -> !FROM.equals(table.getJoinType())).collect(Collectors.toList());
        for (Table table : joinTables) {
            if (!judgeJoinTable(table)) {
                continue;
            }
            sql.append(" ").append(table.getJoinType()).append(" JOIN ").append(table.getName());
            sql.append(" ON ").append(tableQueryConditions.get(table).getJoinCondition());
            if (table.getParameterTempData() != null) {
                executionSql.getParameterTempData().putAll(table.getParameterTempData());
            }
        }
    }

    private boolean judgeJoinTable(Table table) {
        // 非弱表(即强表)则必须Join
        if (!table.isWeak()) {
            return true;
        }
        // 是否有被引用
        return tableQueryConditions.get(table).isReferenced();
    }

    private void appendWhereConditions(StringBuilder sql) {
        StringBuilder whereConditionSql = new StringBuilder();
        for (Table table : queryTables) {
            String conditionSql = tableQueryConditions.get(table).getFilterCondition();
            appendChildCondition(whereConditionSql, conditionSql);
        }
        String conditionSql = buildConditionSql(filterConditions, null, null);
        appendChildCondition(whereConditionSql, conditionSql);
        if (whereConditionSql.length() > 0) {
            sql.append(" WHERE ").append(whereConditionSql);
        }
    }

    private void appendChildCondition(StringBuilder parentSql, String condition) {
        appendChildCondition(parentSql, condition, false);
    }

    private void appendChildCondition(StringBuilder parentSql, String condition, boolean bracketWrap) {
        if (StringUtils.isNotEmpty(condition)) {
            if (parentSql.length() > 0) {
                parentSql.append(" AND ");
            }
            if (bracketWrap) {
                condition = "(" + condition + ")";
            }
            parentSql.append(condition);
        }
    }

    private void appendOrderByConditions(StringBuilder sql) {
        if (enableOrderBy && CollectionUtils.isNotEmpty(orderByConditions)) {
            sql.append(" ORDER BY ").append(String.join(", ", orderByConditions));
        }
    }

    private void appendSqlSnippets(StringBuilder sql) {
        if (CollectionUtils.isNotEmpty(appendSqlSnippets)) {
            sql.append(" ").append(String.join(" ", appendSqlSnippets));
        }
    }

    public SqlBuilder select(String... columnNames) {
        if (ArrayUtils.isNotEmpty(columnNames)) {
            for (String columnName : columnNames) {
                select(columnName, null);
            }
        }
        return this;
    }

    public SqlBuilder select(String columnName, String tableAlias) {
        selectColumns.add(Column.of(columnName, tableAlias));
        return this;
    }

    public SqlBuilder select(Column... columns) {
        if (ArrayUtils.isEmpty(columns)) {
            return this;
        }
        return select(Arrays.asList(columns));
    }

    public SqlBuilder select(List<Column> columns) {
        selectColumns.addAll(columns);
        return this;
    }

    public SqlBuilder fromTable(Table table) {
        table.setJoinType(FROM);
        fromTables.add(table);
        associationTable(table, null);
        return this;
    }

    public SqlBuilder innerJoin(Table table) {
        table.setJoinType(INNER);
        associationTable(table, null);
        return this;
    }

    public SqlBuilder leftJoin(Table table) {
        table.weak().setJoinType(LEFT);
        associationTable(table, null);
        return this;
    }

    public SqlBuilder rightJoin(Table table) {
        table.weak().setJoinType(RIGHT);
        associationTable(table, null);
        return this;
    }

    public SqlBuilder fullJoin(Table table) {
        table.setJoinType(FULL);
        associationTable(table, null);
        return this;
    }

    private void associationTable(Table table, Table previousTable) {
        int index = previousTable == null ? queryTables.size() : queryTables.indexOf(previousTable) + 1;
        queryTables.add(index, table);
    }

    public SqlBuilder filter(String condition, String... associationTableAliases) {
        filterConditions.add(
            Condition.of(condition, ArrayUtils.isEmpty(associationTableAliases) ? Collections.emptyList() : Arrays.asList(associationTableAliases)));
        return this;
    }

    public SqlBuilder orderBy(String condition) {
        orderByConditions.add(condition);
        return this;
    }

    public SqlBuilder append(String sqlSnippet) {
        appendSqlSnippets.add(sqlSnippet);
        return this;
    }

}

        10,核心类之 ExecutionSql

package com.example.dao.sql;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class ExecutionSql {

    private String id;

    private String sql;

    private Map<String, List<?>> parameterTempData = new HashMap<>();

    public ExecutionSql() {
        id = UUID.randomUUID().toString().replace("-", "");
        id = id.substring(id.length() - 10);
    }

    public String getId() {
        return id;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public Map<String, List<?>> getParameterTempData() {
        return parameterTempData;
    }

    public void setParameterTempData(Map<String, List<?>> parameterTempData) {
        this.parameterTempData = parameterTempData;
    }

}

        11,核心类之 BasicConditionQueryCriteria(入参)

package com.example.dao.sql;

import lombok.Data;

import java.util.List;
import java.util.Set;

@Data
public class BasicConditionQueryCriteria implements Cloneable {
    private List<String> name;
    private List<Long> xx;
    private List<Integer> newName;
}

        12,编写测试类

import com.example.DemoApplication;
import com.example.dao.sql.*;
import com.example.entity.DataTemp;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
@Slf4j
public class SqlBuilderTest {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void test1(){
        BasicConditionQueryCriteria queryCriteria = new BasicConditionQueryCriteria();
        queryCriteria.setName(Arrays.asList("1","2"));
        //拼接sql
        List<Column> columns = Arrays.asList(
                Column.of("t11.id","t11"),
                Column.of("t11.name","t11"),
                Column.of("t11.xx","t11"),
                Column.of("T1111.name as newName","T1111")
        );
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.select(columns);
        sqlBuilder.setEnablePlaceholder(false);
        sqlBuilder.fromTable(Table.of("t11 t11")
                .filter(BasicConditionQueryCriteria::getName,"t11.name")
        ).leftJoin(Table.of("T1111 T1111")
                .on("t11.name = T1111.name")
        );

        ExecutionSql executionSql = sqlBuilder.builder(queryCriteria);
        executionSql.setSql(executionSql.getSql() + " order by t11.id");
        log.info("sql:{}",executionSql.getSql());
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(executionSql.getSql());
        maps.stream().forEach(v->{
            v.entrySet().stream().forEach(w->{
                log.info("key:{},value:{}",w.getKey(),w.getValue());
            });
        });

    }



}

        13,项目结构类图

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1647589.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

LSTM计算指示图

掌握网络结构组件构成 输入门、遗忘门、输出门候选记忆细胞记忆细胞隐藏状态ref&#xff1a;6.8. 长短期记忆&#xff08;LSTM&#xff09; — 《动手学深度学习》 文档 (gluon.ai)

[疑难杂症2024-004] 通过docker inspect解决celery多进程记录日志莫名报错的记录

本文由Markdown语法编辑器编辑完成&#xff0e; 1. 前言 最近我负责的一个服务&#xff0c;在医院的服务器上线一段时间后&#xff0c;利用docker logs查看容器的运行日志时&#xff0c;发现会有一个"莫名其妙"的报错&#xff0e;报错的大致内容就是&#xff0c;ce…

vulhub之git(CVE-2017-8386)

启动靶场环境 查看文件 修改属性 为了不和docker母机的ssh端口冲突&#xff0c;将容器的ssh端口设置成3322。本目录下我生成了一个id_rsa&#xff0c;这是ssh的私钥&#xff0c;连接的时候请指定之。在连接以前&#xff0c;需要先设置私钥的权限为0600&#xff1a;chmod 0600 i…

工业光源环形系列一平面无影光源特点

产品特点 ◆LED灯珠均匀排布经过漫射板特殊角度反射达到漫射效果&#xff1a; ◆光源均匀性高&#xff0c;漫射效果好。

11个值得关注的文本转语音AI大模型

语言模型&#xff0c;尤其是大型语言模型&#xff08;LLM&#xff09;&#xff0c;本质上已经成为人工智能的代表。然而&#xff0c;他们有一个隐秘的问题。到目前为止&#xff0c;人工智能社区主要在文本数据上训练人工智能&#xff0c;而忽略了音频数据。结果&#xff0c;我们…

docker-compose完成mysql8.0+环境搭建

1、准备my.cnf文件到指定目录&#xff08;和基础的增加了一个default_authentication_pluginmysql_native_password 的身份验证插件配置信息&#xff09; 原因&#xff1a;官方提到&#xff1a; 该方式可以解决&#xff1a;Authentication plugin ‘caching_ sha2_password‘ c…

《视觉十四讲》例程运行记录(2)——运行ch4的例程评估轨迹误差

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 一、运行ch4的example1. 编译例程2. 运行报错(1) 报错一(2) 报错二 一、运行ch4的example 1. 编译例程 (1) 在slambook2/ch4/example目录下&#xff0c;创建build…

Gradle基础学习(六) 认识任务Task

理解Gradle中的任务 Gradle的构建过程基于任务&#xff08;Task&#xff09;的概念&#xff0c;而每个任务都可以包含一个或多个动作&#xff08;Action&#xff09;。 任务是构建中执行的一些独立的工作单元&#xff0c;例如编译类、创建JAR、生成Javadoc或将存档发布到仓库…

人工智能中的知识表示与推理技术概述

人工智能中的知识表示与推理技术概述 一、引言二、知识表示与推理技术概述1. 描述逻辑2. Horn逻辑3. 产生式系统4. 框架系统5. 语义网络 三、知识表示与推理技术的比较四、知识表示与推理技术的未来发展 一、引言 在人工智能&#xff08;AI&#xff09;的漫长演进中&#xff0…

ICode国际青少年编程竞赛- Python-1级训练场-多变量应用

ICode国际青少年编程竞赛- Python-1级训练场-多变量应用 1、 a 1 b 2 for i in range(4):Spaceship.step(a)Dev.step(b)Dev.step(-b)a a 1b b 12、 a 2 b 5 for i in range(3):Spaceship.turnLeft()Spaceship.step(a)Spaceship.turnRight()Spaceship.step(b)a a …

STM32F103学习笔记 | 报错界面及解决方案 | 1.keil5中文注释的横竖(正与斜)问题

文章目录 一、报错界面二、解决方案参考文献 一、报错界面 二、解决方案 打开设置 在打开的设置选项卡中&#xff0c;图中Font显示的是这个软件当前设置的字体&#xff0c;可以看到字体是仿宋&#xff0c;这就是问题出现的原因&#xff0c;将之改成没有的字体就行了。 可以看…

Dell EMC Storage Unity: Remove/Install Memory Module

SP A 一个内存故障 点击system view -> Enclosures->Top查看 再次查看Alert&#xff0c; 确认内存出现问题 进入Service &#xff0c; 将SP A置为service状态 移出SP A &#xff0c;进行内存更换 更换完内存后&#xff0c;将SP A插入设备&#xff0c;并进行线缆连接 进入…

使用免费的数据恢复软件通过简单的步骤恢复丢失的数据

犯错是人之常情&#xff01;您有时可能会意外地从PC或笔记本电脑中删除重要数据&#xff0c;旧的家庭或大学视频/照片&#xff0c;如果您面临数据丢失&#xff0c;则可以使用数据恢复软件轻松恢复丢失的数据。 奇客数据恢复软件可让您从笔记本电脑&#xff0c;PC和可移动存储设…

VALSE 2024特邀报告内容解析|多模态视觉融合方法:是否存在性能极限?

2024年视觉与学习青年学者研讨会&#xff08;VALSE 2024&#xff09;于5月5日到7日在重庆悦来国际会议中心举行。本公众号将全方位地对会议的热点进行报道&#xff0c;方便广大读者跟踪和了解人工智能的前沿理论和技术。欢迎广大读者对文章进行关注、阅读和转发。文章是对报告人…

五分钟了解等级保护、风险评估和安全测评三者的区别和联系?

等级保护 基本概念&#xff1a;网络安全等级保护是指对国家秘密信息、法人和其他组织和公民的专有信息以及公开信息和存储、传输、处理这些信息的信息系统分等级实行安全保护&#xff0c;对信息系统中使用的安全产品实行按等级管理&#xff0c;对信息系统中发生的信息安全事件…

Linux-03

cat 由第一行开始显示文件内容 tac 从最后一行开始显示&#xff0c;可以看出 tac 是 cat 的倒着写 nl 显示的时候&#xff0c;顺道输出行号 more 一页一页的显示文件内容 less 与 more 类似&#xff0c;但是比 more 更好的是&#xff0c;他可以往前翻页 (空格翻页 退出q命令) h…

不是,有你们这么卖东西的?涨价是肯定的,我苟住不浪也是必然的!——早读(逆天打工人爬取热门微信文章解读)

大家说我苟&#xff0c;我笑他人看不穿 引言Python 代码第一篇 洞见 晕船法则&#xff08;深度好文&#xff09;第二篇 九边 宅男之死结尾 理性的讨论能够促进理解 而不仅仅是赢得争论 我们追求的是通过讨论增进理解 而非仅仅证明自己的正确 引言 最近的言论似乎控制得更加严格…

Study--Oracle-01-单实例部署Oracle11G-R2

Oracle版本发布介绍 Oracle 19c和12c和11g功能区别_数据库_oracle_支持 一、CentOS 7 环境准备 1、软件准备 操作系统&#xff1a;CentOS 7 数据库版本: Oracle11g R2 2、操作系统环境配置 关闭selinux &#xff0c;编辑 /etc/selinux/config文件&#xff0c;设置SELINU…

Elementui的el-footer标签使用报错

Elementui的el-footer标签使用报错 其余标签的使用没有报错信息 el-footer的报错信息 原因: ​ 警告信息表示 Vue 不识别 <el-footer> 解决方式: 在组件中进行引入和暴露

Ai时代使用语音笔记整理文稿提高创作效率

其实传统的创作方式是用钢笔或者圆珠笔手写草稿。成稿后花钱誊抄数份邮寄给出版商。 计算机普及后&#xff0c;有人开始直接使用打字机或计算机创做&#xff0c;打字其实要比手写的速度快数倍&#xff0c;这样效率的提升&#xff0c;加上文创平台基本上都是按字数给收益&#…