From ce04dfcdd664df7e791a63800cab2cd2d12e878c Mon Sep 17 00:00:00 2001 From: liulin <lin.liu@aliyun.com> Date: 星期二, 30 七月 2024 00:06:41 +0800 Subject: [PATCH] 适配mybatis-plus --- /dev/null | 1939 ------------------------------------------------- src/main/java/com/lunhan/xxx/repository/mapper/TestInfoMapperImpl.java | 127 +++ src/main/java/com/lunhan/xxx/repository/BasicPO.java | 6 src/main/java/com/lunhan/xxx/repository/imapper/TestInfoMapper.java | 4 src/main/java/com/lunhan/xxx/service/convert/TestInfoConvert.java | 0 src/main/java/com/lunhan/xxx/repository/BasicMapper.java | 4 src/main/java/com/lunhan/xxx/repository/BasicMapperImpl.java | 260 ++++++ 7 files changed, 401 insertions(+), 1,939 deletions(-) diff --git a/src/main/java/com/lunhan/xxx/common/orm2/ColumnBuilder.java b/src/main/java/com/lunhan/xxx/common/orm2/ColumnBuilder.java deleted file mode 100644 index 852bc87..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/ColumnBuilder.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.lunhan.xxx.common.orm2; - -import com.lunhan.xxx.common.orm2.enums.ColumnBasic; -import com.lunhan.xxx.common.orm2.enums.EnumCondition; -import com.lunhan.xxx.common.orm2.models.SqlCondition; -import com.lunhan.xxx.common.orm2.models.SqlParameter; -import com.lunhan.xxx.common.util.StringUtil; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class ColumnBuilder { - public static String getColumnName(String tableName, String columnName) { - return tableName + "." + columnName; - } - - public static SqlCondition equal(String columnName, Object value) { - return createSqlCondition(EnumCondition.EQUAL, columnName, value); - } - - public static SqlCondition notEqual(String columnName, Object value) { - return createSqlCondition(EnumCondition.NOT_EQUAL, columnName, value); - } - - public static SqlCondition lessThan(String columnName, Object value) { - return createSqlCondition(EnumCondition.LESS_THAN, columnName, value); - } - - public static SqlCondition lessOrEqual(String columnName, Object value) { - return createSqlCondition(EnumCondition.LESS_OR_EQUAL, columnName, value); - } - - public static SqlCondition greaterThan(String columnName, Object value) { - return createSqlCondition(EnumCondition.GREATER_THAN, columnName, value); - } - - public static SqlCondition greaterOrEqual(String columnName, Object value) { - return createSqlCondition(EnumCondition.GREATER_OR_EQUAL, columnName, value); - } - - public static SqlCondition like(String columnName, Object value) { - return createSqlCondition(EnumCondition.LIKE, columnName, "%" + value.toString() + "%"); - } - - public static SqlCondition rightLike(String columnName, Object value) { - return createSqlCondition(EnumCondition.LIKE, columnName, value.toString() + "%"); - } - - public static SqlCondition notLike(String columnName, Object value) { - return createSqlCondition(EnumCondition.NOT_LIKE, columnName, "%" + value.toString() + "%"); - } - - public static SqlCondition notRightLike(String columnName, Object value) { - return createSqlCondition(EnumCondition.NOT_LIKE, columnName, value.toString() + "%"); - } - - public static SqlCondition in(String columnName, Object value) { - return createSqlCondition(EnumCondition.IN, columnName, value); - } - - public static SqlCondition notIn(String columnName, Object value) { - return createSqlCondition(EnumCondition.NOT_IN, columnName, value); - } - - public static String desc(String columnName) { - return columnName + EnumCondition.DESC.getCond(); - } - - public static String asc(String columnName) { - return columnName + EnumCondition.ASC.getCond(); - } - - //*******************************************************************// - - private static SqlCondition createSqlCondition(EnumCondition cond, String columnName, Object value) { - String sql = columnName + cond.getCond(); - List<SqlParameter> paramList = new ArrayList<>(); - - if (value instanceof ColumnBasic) { - sql += ((ColumnBasic) value).getColumnName(); - paramList.add(new SqlParameter(columnName, value, null)); - } else if (value instanceof Collection) { - SqlCondition splitResult = splitValue(columnName, ((Collection) value).toArray(), sql); - sql = splitResult.getSql(); - paramList.addAll(splitResult.getParamList()); - } else if (value.getClass().isArray()) { - SqlCondition splitResult = splitValue(columnName, value, sql); - sql = splitResult.getSql(); - paramList.addAll(splitResult.getParamList()); - } else { - sql += "?"; - Integer paramType = SqlUtil.getParameterType(value); - paramList.add(new SqlParameter(columnName, value, paramType)); - } - return new SqlCondition(sql, paramList); - } - - private static SqlCondition splitValue(String columnName, Object value, String sql) { - List<SqlParameter> paramList = new ArrayList<>(); - List<String> placeList = new ArrayList<>(); - - int length = Array.getLength(value); - if (length == 0) { - return new SqlCondition("(1=2)", paramList); - } - - for (int i = 0; i < length; i++) { - Object item = Array.get(value, i); - Integer paramType = SqlUtil.getParameterType(item); - paramList.add(new SqlParameter(columnName + "_" + i, item, paramType)); - placeList.add("?"); - } - return new SqlCondition(sql + "(" + StringUtil.join(placeList, ",") + ")", paramList); - } -} diff --git a/src/main/java/com/lunhan/xxx/common/orm2/SqlBuilder.java b/src/main/java/com/lunhan/xxx/common/orm2/SqlBuilder.java deleted file mode 100644 index 5c194e5..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/SqlBuilder.java +++ /dev/null @@ -1,430 +0,0 @@ -package com.lunhan.xxx.common.orm2; - -import com.lunhan.xxx.common.ConstantFactory; -import com.lunhan.xxx.common.orm2.enums.ColumnBasic; -import com.lunhan.xxx.common.orm2.enums.EnumBuildType; -import com.lunhan.xxx.common.orm2.enums.EnumSqlType; -import com.lunhan.xxx.common.orm2.models.SqlCondition; -import com.lunhan.xxx.common.orm2.models.SqlParameter; -import com.lunhan.xxx.common.util.ListUtil; -import com.lunhan.xxx.common.util.NumericUtil; -import com.lunhan.xxx.common.util.StringUtil; -import org.apache.commons.lang3.BooleanUtils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Sql生成器 - * - * @author yufq - * @date 2021-4-9 - */ -public class SqlBuilder { - private EnumBuildType buildType; - private List<String> selectColumnList; - private String fromTableName; - private List<String> joinTableList; - private List<SqlCondition> setList; - private List<SqlCondition> whereList; - private List<SqlCondition> condList; - private List<String> orderByList; - private Integer skipIndex; - private Integer takeNum; - - public Integer getPageSize() { - return NumericUtil.tryParseInt(takeNum, 0); - } - public Integer getPageIndex() { - return NumericUtil.tryParseInt(skipIndex, 0) / NumericUtil.tryParseInt(takeNum, 1) + 1; - } - - public SqlBuilder() { - this.buildType = EnumBuildType.SELECT; - this.selectColumnList = new ArrayList<>(); - this.joinTableList = new ArrayList<>(); - this.setList = new ArrayList<>(); - this.whereList = new ArrayList<>(); - this.condList = new ArrayList<>(); - this.orderByList = new ArrayList<>(); - } - - public SqlBuilder select(ColumnBasic... columns) { - String[] columnNames = new String[columns.length]; - for (int i = 0; i < columns.length; i++) { - columnNames[i] = columns[i].getColumnName(); - } - this.select(columnNames); - return this; - } - - public SqlBuilder select(String... columns) { - buildType = EnumBuildType.SELECT; - selectColumnList.addAll(Arrays.asList(columns)); - return this; - } - - public SqlBuilder update(String tableName) { - buildType = EnumBuildType.UPDATE; - this.fromTableName = tableName; - return this; - } - - public SqlBuilder delete(String tableName) { - buildType = EnumBuildType.DELETE; - this.fromTableName = tableName; - return this; - } - - public SqlBuilder insert(String tableName) { - buildType = EnumBuildType.INSERT; - this.fromTableName = tableName; - return this; - } - - public SqlBuilder from(String tableName) { - this.fromTableName = tableName; - return this; - } - - public SqlBuilder join(String tableName, ColumnBasic columnA, ColumnBasic columnB) { - joinTableList.add(String.format(" JOIN %s ON %s = %s", tableName, columnA.getColumnName(), columnB.getColumnName())); - return this; - } - - public SqlBuilder join(String tableName, String columnA, String columnB) { - joinTableList.add(String.format(" JOIN %s ON %s = %s", tableName, columnA, columnB)); - return this; - } - - public SqlBuilder leftJoin(String tableName, ColumnBasic columnA, ColumnBasic columnB) { - joinTableList.add(String.format(" LEFT JOIN %s ON %s = %s", tableName, columnA.getColumnName(), columnB.getColumnName())); - return this; - } - - public SqlBuilder leftJoin(String tableName, String columnA, String columnB) { - joinTableList.add(String.format(" LEFT JOIN %s ON %s = %s", tableName, columnA, columnB)); - return this; - } - - public SqlBuilder set(ColumnBasic column, Object value) { - this.setList.add(column.equal(value)); - return this; - } - - public SqlBuilder set(SqlCondition param) { - this.setList.add(param); - return this; - } - - public SqlBuilder where(SqlCondition param) { - this.whereList.add(param); - return this; - } - - public SqlBuilder and(SqlCondition cond) { - String sql = cond.getSql(); - if (this.isAddCond()) { - sql = ConstantFactory.SQL_AND + " " + sql; - } - this.condList.add(new SqlCondition(sql, cond.getParamList())); - return this; - } - - public SqlBuilder and(SqlBuilder builder) { - SqlCondition buildResult = builder.whereBuild(); - String sql = "(" + buildResult.getSql() + ")"; - if (this.isAddCond()) { - sql = ConstantFactory.SQL_AND + " " + sql; - } - this.condList.add(new SqlCondition(sql, buildResult.getParamList())); - return this; - } - - public SqlBuilder andIf(Boolean condition, SqlCondition cond) { - if (BooleanUtils.isTrue(condition)) { - this.and(cond); - } - return this; - } - - public SqlBuilder andIf(Boolean condition, SqlBuilder builder) { - if (BooleanUtils.isTrue(condition)) { - this.and(builder); - } - return this; - } - - public SqlBuilder or(SqlCondition cond) { - String sql = cond.getSql(); - if (this.isAddCond()) { - sql = ConstantFactory.SQL_OR + " " + cond.getSql(); - } - this.condList.add(new SqlCondition(sql, cond.getParamList())); - return this; - } - - public SqlBuilder or(SqlBuilder builder) { - SqlCondition buildResult = builder.whereBuild(); - String sql = "(" + buildResult.getSql() + ")"; - if (this.isAddCond()) { - sql = ConstantFactory.SQL_OR + " " + sql; - } - this.condList.add(new SqlCondition(sql, buildResult.getParamList())); - return this; - } - - public SqlBuilder orIf(Boolean condition, SqlCondition cond) { - if (BooleanUtils.isTrue(condition)) { - this.or(cond); - } - return this; - } - - public SqlBuilder orIf(Boolean condition, SqlBuilder builder) { - if (BooleanUtils.isTrue(condition)) { - this.or(builder); - } - return this; - } - - public SqlBuilder orderBy(String... columns) { - this.orderByList.addAll(Arrays.asList(columns)); - return this; - } - - public SqlBuilder skip(Integer skipIndex) { - this.skipIndex = skipIndex; - return this; - } - - public SqlBuilder take(Integer takeNum) { - this.takeNum = takeNum; - return this; - } - - public SqlBuilder page(Integer pageIndex, Integer pageSize) { - this.skipIndex = pageSize * (pageIndex - 1); - this.takeNum = pageSize; - return this; - } - - public SqlCondition count() { - StringBuilder sql = new StringBuilder(); - List<SqlParameter> paramList = new ArrayList<>(); - sql.append("SELECT COUNT(*)"); - if (StringUtil.isNotNullOrEmpty(this.fromTableName)) { - sql.append(" FROM "); - sql.append(this.fromTableName); - } - if (ListUtil.isNotNullOrEmpty(this.joinTableList)) { - for (String joinTable : this.joinTableList) { - sql.append(joinTable); - } - } - SqlCondition whereCond = this.whereBuild(); - if (this.whereList.isEmpty() && BooleanUtils.isFalse(condList.isEmpty())) { - sql.append(" WHERE "); - } - sql.append(whereCond.getSql()); - paramList.addAll(whereCond.getParamList()); - return new SqlCondition(sql.toString(), paramList); - } - - public SqlCondition build() { - return this.build(EnumSqlType.DEFAULT); - } - - public SqlCondition build(EnumSqlType sqlType) { - //参数处理 - this.paramSort(); - - SqlCondition sqlCondition; - switch (this.buildType) { - case SELECT: - sqlCondition = this.selectBuild(); - break; - case UPDATE: - sqlCondition = this.updateBuild(); - break; - case DELETE: - sqlCondition = this.deleteBuild(); - break; - case INSERT: - sqlCondition = this.insertBuild(); - break; - default: - return null; - } - - if (EnumSqlType.MYBATIS.equals(sqlType)) { - sqlCondition = this.getSqlMyBatis(sqlCondition); - } - return sqlCondition; - } - - public String log() { - return this.log(EnumSqlType.DEFAULT); - } - - public String log(EnumSqlType sqlType) { - SqlCondition buildResult = this.build(sqlType); - String sql = buildResult.getSql(); - List<String> paramList = new ArrayList<>(); - for (SqlParameter param : buildResult.getParamList()) { - paramList.add(param.getName() + "=" + param.getValue()); - } - return sql + " [" + StringUtil.join(paramList, ",") + "]"; - } - - //***************************************************************************// - - private boolean isAddCond() { - if (ListUtil.isNotNullOrEmpty(this.whereList) || ListUtil.isNotNullOrEmpty(this.condList)) { - return true; - } - return false; - } - - private SqlCondition selectBuild() { - StringBuilder sql = new StringBuilder(); - List<SqlParameter> paramList = new ArrayList<>(); - if (ListUtil.isNotNullOrEmpty(this.selectColumnList)) { - sql.append("SELECT "); - sql.append(StringUtil.join(this.selectColumnList, ConstantFactory.SQL_STR_COMMA)); - } - if (StringUtil.isNotNullOrEmpty(this.fromTableName)) { - sql.append(" FROM "); - sql.append(this.fromTableName); - } - if (ListUtil.isNotNullOrEmpty(this.joinTableList)) { - for (String joinTable : this.joinTableList) { - sql.append(joinTable); - } - } - SqlCondition whereCond = this.whereBuild(); - if (this.whereList.isEmpty() && BooleanUtils.isFalse(condList.isEmpty())) { - sql.append(" WHERE "); - } - sql.append(whereCond.getSql()); - paramList.addAll(whereCond.getParamList()); - if (ListUtil.isNotNullOrEmpty(this.orderByList)) { - sql.append(" ORDER BY "); - sql.append(StringUtil.join(this.orderByList, ConstantFactory.SQL_STR_COMMA)); - } - if (skipIndex != null || takeNum != null) { - sql.append(String.format(" LIMIT %s,%s ", NumericUtil.tryParseInt(skipIndex, 0), NumericUtil.tryParseInt(takeNum, 0))); - } - return new SqlCondition(sql.toString(), paramList); - } - - private SqlCondition updateBuild() { - StringBuilder sql = new StringBuilder(); - List<SqlParameter> paramList = new ArrayList<>(); - sql.append("UPDATE "); - sql.append(fromTableName); - if (ListUtil.isNotNullOrEmpty(this.setList)) { - sql.append(" SET "); - for (int i = 0; i < this.setList.size(); i++) { - SqlCondition setCond = this.setList.get(i); - if (i > 0) { - sql.append(ConstantFactory.SQL_STR_COMMA); - } - sql.append(setCond.getSql()); - paramList.addAll(setCond.getParamList()); - } - } - SqlCondition whereCond = this.whereBuild(); - if (this.whereList.isEmpty() && BooleanUtils.isFalse(condList.isEmpty())) { - sql.append(" WHERE "); - } - sql.append(whereCond.getSql()); - paramList.addAll(whereCond.getParamList()); - return new SqlCondition(sql.toString(), paramList); - } - - private SqlCondition deleteBuild() { - StringBuilder sql = new StringBuilder(); - List<SqlParameter> paramList = new ArrayList<>(); - sql.append("DELETE FROM "); - sql.append(fromTableName); - SqlCondition whereCond = this.whereBuild(); - if (this.whereList.isEmpty() && BooleanUtils.isFalse(condList.isEmpty())) { - sql.append(" WHERE "); - } - sql.append(whereCond.getSql()); - paramList.addAll(whereCond.getParamList()); - return new SqlCondition(sql.toString(), paramList); - } - - private SqlCondition insertBuild() { - StringBuilder sql = new StringBuilder(); - List<SqlParameter> paramList = new ArrayList<>(); - sql.append("INSERT INTO "); - sql.append(fromTableName); - if (ListUtil.isNotNullOrEmpty(this.setList)) { - sql.append(" ("); - for (int i = 0; i < this.setList.size(); i++) { - SqlCondition setCond = this.setList.get(i); - if (i > 0) { - sql.append(ConstantFactory.SQL_STR_COMMA); - } - String name = setCond.getParamList().get(0).getName(); - sql.append(name.substring(0, name.indexOf("."))); - paramList.addAll(setCond.getParamList()); - } - sql.append(") VALUES("); - List<String> listWen = this.setList.stream() - .map(c -> "?") - .collect(Collectors.toList()); - sql.append(StringUtil.join(listWen)); - sql.append(")"); - } - sql.append(";"); - return new SqlCondition(sql.toString(), paramList); - } - - private SqlCondition whereBuild() { - StringBuilder sql = new StringBuilder(); - List<SqlParameter> paramList = new ArrayList<>(); - if (ListUtil.isNotNullOrEmpty(this.whereList)) { - sql.append(" WHERE "); - for (SqlCondition whereCond : this.whereList) { - sql.append(whereCond.getSql()); - paramList.addAll(whereCond.getParamList()); - } - } - if (ListUtil.isNotNullOrEmpty(this.condList)) { - for (SqlCondition whereCond : this.condList) { - sql.append(whereCond.getSql()); - paramList.addAll(whereCond.getParamList()); - } - } - return new SqlCondition(sql.toString(), paramList); - } - - private SqlCondition getSqlMyBatis(SqlCondition sqlCondition) { - List<SqlParameter> paramList = new ArrayList<>(); - sqlCondition.getParamList().stream().forEach(a -> { - paramList.add(new SqlParameter(String.format("#{%s}", a.getName()), a.getValue(), a.getType())); - }); - - String sql = sqlCondition.getSql(); - sql = sql.replace("?", "%s"); - sql = String.format(sql, paramList.stream().map(SqlParameter::getName).toArray()); - return new SqlCondition(sql, paramList); - } - - private void paramSort() { - List<SqlParameter> paramList = new ArrayList<>(); - this.setList.stream().forEach(item -> paramList.addAll(item.getParamList())); - this.whereList.stream().forEach(item -> paramList.addAll(item.getParamList())); - this.condList.stream().forEach(item -> paramList.addAll(item.getParamList())); - paramList.stream().forEach(param -> { - String name = param.getName() + "." + paramList.indexOf(param); - param.setName(name); - }); - } -} diff --git a/src/main/java/com/lunhan/xxx/common/orm2/SqlUtil.java b/src/main/java/com/lunhan/xxx/common/orm2/SqlUtil.java deleted file mode 100644 index aeae110..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/SqlUtil.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.lunhan.xxx.common.orm2; - -import com.lunhan.xxx.common.ConstantFactory; -import com.lunhan.xxx.common.util.CalendarUtil; -import com.lunhan.xxx.common.util.NumericUtil; - -import java.math.BigDecimal; -import java.sql.Types; -import java.util.Date; - -/** - * 处理sql 相关工具类 - */ -public final class SqlUtil { - private SqlUtil() { - throw new IllegalStateException("Utility class"); - } - - /** - * 获取java类型对应的sql数据类型 - * @param value 参数值 - */ - public static Integer getParameterType(Object value) { - Integer type = Types.VARCHAR; - - if (value instanceof Integer) { - type = Types.INTEGER; - } else if (value instanceof Long) { - type = Types.BIGINT; - } else if (value instanceof Float) { - type = Types.DECIMAL; - } else if (value instanceof Double) { - type = Types.DECIMAL; - } else if (value instanceof Boolean) { - type = Types.BOOLEAN; - } else if (value instanceof CalendarUtil) { - type = Types.TIME; - } else if (value instanceof Date) { - type = Types.TIMESTAMP; - } else if (value instanceof BigDecimal) { - type = Types.DECIMAL; - } - return type; - } - - /** - * 构建in的where条件 - * @param inQuantity in条件个数 - */ - public static String getListInWhereSql(Integer inQuantity) { - if(NumericUtil.tryParseInt(inQuantity).compareTo(0)<1) { - return " 1!=1"; - } - StringBuilder sbSql = new StringBuilder(); - sbSql.append("("); - for (int i=0; i<inQuantity; i++) { - if(i>0) { - sbSql.append(ConstantFactory.SQL_STR_COMMA); - } - sbSql.append("?"); - } - sbSql.append(")"); - return sbSql.toString(); - } -} \ No newline at end of file diff --git a/src/main/java/com/lunhan/xxx/common/orm2/enums/ColumnBasic.java b/src/main/java/com/lunhan/xxx/common/orm2/enums/ColumnBasic.java deleted file mode 100644 index 4743d50..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/enums/ColumnBasic.java +++ /dev/null @@ -1,193 +0,0 @@ -package com.lunhan.xxx.common.orm2.enums; - -import com.lunhan.xxx.common.orm2.ColumnBuilder; -import com.lunhan.xxx.common.orm2.models.SqlCondition; - -public interface ColumnBasic { - /** - * 获取列名 - * - * @return - */ - String getColumnName(); - - /** - * = - * 等于 - * - * @return - */ - default SqlCondition equal(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.equal(this.getColumnName(), value); - } - - /** - * <> - * 不等于 - * - * @return - */ - default SqlCondition notEqual(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.notEqual(this.getColumnName(), value); - } - - /** - * < - * 小于 - * - * @return - */ - default SqlCondition lessThan(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.lessThan(this.getColumnName(), value); - } - - /** - * <= - * 小于等于 - * - * @return - */ - default SqlCondition lessOrEqual(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.lessOrEqual(this.getColumnName(), value); - } - - /** - * > - * 大于 - * - * @return - */ - default SqlCondition greaterThan(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.greaterThan(this.getColumnName(), value); - } - - /** - * >= - * 大于等于 - * - * @return - */ - default SqlCondition greaterOrEqual(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.greaterOrEqual(this.getColumnName(), value); - } - - /** - * like - * 全模糊匹配 %xxx% - * - * @param value - * @return - */ - default SqlCondition like(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.like(this.getColumnName(), value); - } - - /** - * like - * 右模糊匹配 xxx% - * - * @param value - * @return - */ - default SqlCondition rightLike(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.rightLike(this.getColumnName(), value); - } - - /** - * not like - * 全模糊不匹配 %xxx% - * - * @param value - * @return - */ - default SqlCondition notLike(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.notLike(this.getColumnName(), value); - } - - /** - * not like - * 右模糊不匹配 xxx% - * - * @param value - * @return - */ - default SqlCondition notRightLike(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.notRightLike(this.getColumnName(), value); - } - - /** - * in - * 多个值匹配 - * - * @param value - * @return - */ - default SqlCondition in(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.in(this.getColumnName(), value); - } - - /** - * not in - * 多个值不匹配 - * - * @param value - * @return - */ - default SqlCondition notIn(Object value) { - if (null == value) { - return null; - } - return ColumnBuilder.notIn(this.getColumnName(), value); - } - - /** - * desc - * 降序 - */ - default String desc() { - return ColumnBuilder.desc(this.getColumnName()); - } - - /** - * asc - * 升序 - * - * @return - */ - default String asc() { - return ColumnBuilder.asc(this.getColumnName()); - } -} diff --git a/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumBuildType.java b/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumBuildType.java deleted file mode 100644 index 41b919d..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumBuildType.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.lunhan.xxx.common.orm2.enums; - -public enum EnumBuildType { - SELECT("select", 1), - UPDATE("update", 2), - DELETE("delete", 3), - INSERT("insert", 4); - - private String code; - private Integer value; - - EnumBuildType(String code, Integer value) { - this.code = code; - this.value = value; - } -} diff --git a/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumCondition.java b/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumCondition.java deleted file mode 100644 index 7ba25e7..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumCondition.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.lunhan.xxx.common.orm2.enums; - -import java.util.Arrays; -import java.util.Objects; - -public enum EnumCondition { - EQUAL(" = ", 1), - NOT_EQUAL(" <> ", 2), - LESS_THAN(" < ", 3), - LESS_OR_EQUAL(" <= ", 4), - GREATER_THAN(" > ", 5), - GREATER_OR_EQUAL(" >= ", 6), - LIKE(" LIKE ", 7), - NOT_LIKE(" NOT LIKE ", 8), - IN(" IN ", 9), - NOT_IN(" NOT IN ", 10), - DESC(" DESC ", 11), - ASC(" ASC ", 12); - - private String cond; - private Integer value; - - EnumCondition(String cond, Integer value) { - this.cond = cond; - this.value = value; - } - - public String getCond() { - return cond; - } - - public Integer getValue() { - return value; - } - - /** - * 根据值获取枚举 - * - * @param value 枚举值 - * @return - */ - public static EnumCondition getByValue(Integer value) { - return Arrays.stream(EnumCondition.values()) - .filter(e -> Objects.equals(e.getValue(), value)) - .findAny() - .orElse(null); - } - - @Override - public String toString() { - return "EConditionType{" + - "cond='" + cond + '\'' + - ", value=" + value + - '}'; - } -} diff --git a/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumSqlType.java b/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumSqlType.java deleted file mode 100644 index 1c7dea1..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/enums/EnumSqlType.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.lunhan.xxx.common.orm2.enums; - -public enum EnumSqlType { - DEFAULT("default", 1), - MYBATIS("mybatis", 2); - - private String code; - private Integer value; - - EnumSqlType(String code, Integer value) { - this.code = code; - this.value = value; - } -} diff --git a/src/main/java/com/lunhan/xxx/common/orm2/gencolumn/GenColumnMySql.java b/src/main/java/com/lunhan/xxx/common/orm2/gencolumn/GenColumnMySql.java deleted file mode 100644 index 9a8f8ea..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/gencolumn/GenColumnMySql.java +++ /dev/null @@ -1,217 +0,0 @@ -package com.lunhan.xxx.common.orm2.gencolumn; - -import org.apache.commons.lang3.StringUtils; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.sql.*; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * 生成数据库列 MySql - */ -public class GenColumnMySql { - private final Connection conn; - private String outFilePath; - - public GenColumnMySql(String url, String name, String password, String driver) throws ClassNotFoundException, SQLException { - //加载驱动 - Class.forName(driver); - //获得连接 - conn = DriverManager.getConnection(url, name, password); - } - - public boolean run(String packageName, List<String> importList, String outPath) throws Exception { - if (conn == null || conn.isClosed()) { - return false; - } - - outFilePath = new File("").getAbsolutePath() + "/" + outPath + "/" + packageName.replace(".", "/"); - System.out.println("outFilePath:" + outFilePath); - File directory = new File(outFilePath); - directory.mkdirs(); - - try { - Map<String, String> tableInfo = this.getTableInfo(conn.getCatalog()); - for (Map.Entry<String, String> item : tableInfo.entrySet()) { - String tableName = item.getKey(); - String tableComment = item.getValue(); - Map<String, String> columnInfoMap = this.getColumnInfo(tableName); - this.createColumnFile(tableName, tableComment, columnInfoMap, packageName, importList); - } - } finally { - conn.close(); - } - return true; - } - - private Map<String, String> getTableInfo(String tableSchema) throws SQLException { - Map<String, String> tableInfoMap = new LinkedHashMap<>(); - String sql = " SELECT TABLE_NAME ,TABLE_COMMENT " + - " FROM information_schema.`TABLES` " + - " WHERE TABLE_SCHEMA = ? "; - try (PreparedStatement pStmt = conn.prepareStatement(sql)) { - pStmt.setString(1, tableSchema); - try (ResultSet rs = pStmt.executeQuery()) { - while (rs.next()) { - String tableName = rs.getString("TABLE_NAME"); - String tableComment = rs.getString("TABLE_COMMENT"); - tableInfoMap.put(tableName, tableComment); - } - } - } - return tableInfoMap; - } - - private Map<String, String> getColumnInfo(String tableName) throws SQLException { - Map<String, String> columnInfoMap = new LinkedHashMap<>(); - String sql = " SELECT COLUMN_NAME ,COLUMN_COMMENT " + - " FROM information_schema.`COLUMNS` " + - " WHERE TABLE_NAME = ? "; - try (PreparedStatement pStmt = conn.prepareStatement(sql)) { - pStmt.setString(1, tableName); - try (ResultSet rs = pStmt.executeQuery()) { - while (rs.next()) { - String columnName = rs.getString("COLUMN_NAME"); - String columnComment = rs.getString("COLUMN_COMMENT"); - columnInfoMap.put(columnName, columnComment); - } - } - } - return columnInfoMap; - } - - private void createColumnFile(String tableName, String tableComment, Map<String, String> columnInfoMap, String packageName, List<String> importList) throws IOException { - String fileName = this.underline2Camel(tableName, true); - String filePath = this.outFilePath + "/" + fileName + ".java"; - - File columnFile = new File(filePath); - columnFile.createNewFile(); - - StringBuilder sb = new StringBuilder(); - sb.append("/*\n" + - "# __----~~~~~~~~~~~------___\n" + - "# . . ~~//====...... __--~ ~~\n" + - "# -. \\_|// |||\\\\ ~~~~~~::::... /~\n" + - "# ___-==_ _-~o~ \\/ ||| \\\\ _/~~-\n" + - "# __---~~~.==~||\\=_ -_--~/_-~|- |\\\\ \\\\ _/~\n" + - "# _-~~ .=~ | \\\\-_ '-~7 /- / || \\ /\n" + - "# .~ .~ | \\\\ -_ / /- / || \\ /\n" + - "# / ____ / | \\\\ ~-_/ /|- _/ .|| \\ /\n" + - "# |~~ ~~|--~~~~--_ \\ ~==-/ | \\~--===~~ .\\\n" + - "# ' ~-| /| |-~\\~~ __--~~\n" + - "# |-~~-_/ | | ~\\_ _-~ /\\\n" + - "# / \\ \\__ \\/~ \\__\n" + - "# _--~ _/ | .-~~____--~-/ ~~==.\n" + - "# ((->/~ '.|||' -_| ~~-/ , . _||\n" + - "# -_ ~\\ ~~---l__i__i__i--~~_/\n" + - "# _-~-__ ~) \\--______________--~~\n" + - "# //.-~~~-~_--~- |-------~~~~~~~~\n" + - "# //.-~~~--\\\n" + - "# 神兽保佑\n" + - "# 代码无BUG! \n" + - "*/"); - sb.append("\r\n"); - sb.append(String.format("package %s;%n", packageName)); - sb.append("\r\n"); - for (String item : importList) { - sb.append(String.format("import %s;%n", item)); - } - sb.append("\r\n"); - sb.append("/**\r\n"); - sb.append(String.format(" * %s%n", tableComment)); - sb.append(" */\r\n"); - sb.append(String.format("public enum %s implements ColumnBasic {%n", fileName)); - int index = 1; - for (Map.Entry<String, String> item : columnInfoMap.entrySet()) { - String columnName = item.getKey(); - String columnComment = item.getValue(); - sb.append(" /**\r\n"); - sb.append(String.format(" * %s%n", columnComment.replace("\r\n", "\r\n * "))); - sb.append(" */\r\n"); - sb.append(String.format(" %s(\"%s\", %s),%n", columnName.toUpperCase(), columnName, index++)); - } - sb.replace(sb.lastIndexOf(","), sb.length(), ";\r\n"); - sb.append("\r\n"); - sb.append(" private String columnName;\r\n"); - sb.append(" private Integer columnIndex;\r\n"); - sb.append(String.format(" public static final String TABLE_NAME = \"%s\";%n", tableName)); - sb.append("\r\n"); - sb.append(String.format(" %s(String columnName, Integer columnIndex) {%n", fileName)); - sb.append(" this.columnName = columnName;\r\n"); - sb.append(" this.columnIndex = columnIndex;\r\n"); - sb.append(" }\r\n"); - sb.append("\r\n"); - sb.append(" @Override\r\n"); - sb.append(" public String getColumnName() {\r\n"); - sb.append(" return ColumnBuilder.getColumnName(TABLE_NAME, this.columnName);\r\n"); - sb.append(" }\r\n"); - sb.append("}"); - - try (FileWriter fw = new FileWriter(columnFile.getAbsolutePath()); - PrintWriter pw = new PrintWriter(fw)) { - pw.println(sb.toString()); - pw.flush(); - } - } - - private String underline2Camel(String line, boolean... firstIsUpperCase) { - String str = ""; - if (StringUtils.isBlank(line)) { - return str; - } else { - StringBuilder sb = new StringBuilder(); - String[] strArr; - // 不包含下划线,且第二个参数是空的 - if (!line.contains("_") && firstIsUpperCase.length == 0) { - sb.append(line.substring(0, 1).toLowerCase()).append(line.substring(1)); - str = sb.toString(); - } else if (!line.contains("_") && firstIsUpperCase.length != 0) { - if (!firstIsUpperCase[0]) { - sb.append(line.substring(0, 1).toLowerCase()).append(line.substring(1)); - str = sb.toString(); - } else { - sb.append(line.substring(0, 1).toUpperCase()).append(line.substring(1)); - str = sb.toString(); - } - } else if (line.contains("_") && firstIsUpperCase.length == 0) { - strArr = line.split("_"); - for (String s : strArr) { - sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1)); - } - str = sb.toString(); - str = str.substring(0, 1).toLowerCase() + str.substring(1); - } else if (line.contains("_") && firstIsUpperCase.length != 0) { - strArr = line.split("_"); - for (String s : strArr) { - sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1)); - } - if (!firstIsUpperCase[0]) { - str = sb.toString(); - str = str.substring(0, 1).toLowerCase() + str.substring(1); - } else { - str = sb.toString(); - } - } - } - return str; - } - -// public static void main(String[] args) throws Exception { -// String url = "jdbc:mysql://81.68.189.38:3306/mall-test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false"; -// String name = "root"; -// String password = "root"; -// String driver = "com.mysql.jdbc.Driver"; -// String outPath = "framework-common/src/test/java"; -// String packageName = "com.ctrip.tour.cq.framework.common.test.dbcoulmns.orms"; -// List<String> importList = new ArrayList() {{ -// add("com.ctrip.tour.cq.framework.common.orm2.ColumnBuilder"); -// add("com.ctrip.tour.cq.framework.common.orm2.enums.ColumnBasic"); -// }}; -// new GenColumnMySql(url, name, password, driver).run(packageName, importList, outPath); -// } -} diff --git a/src/main/java/com/lunhan/xxx/common/orm2/models/SqlCondition.java b/src/main/java/com/lunhan/xxx/common/orm2/models/SqlCondition.java deleted file mode 100644 index 1e08990..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/models/SqlCondition.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.lunhan.xxx.common.orm2.models; - -import java.util.List; - -public class SqlCondition { - private String sql; - private List<SqlParameter> paramList; - - public SqlCondition(String sql, List<SqlParameter> paramList) { - this.sql = sql; - this.paramList = paramList; - } - - public String getSql() { - return sql; - } - - public void setSql(String sql) { - this.sql = sql; - } - - public List<SqlParameter> getParamList() { - return paramList; - } - - public void setParamList(List<SqlParameter> paramList) { - this.paramList = paramList; - } -} diff --git a/src/main/java/com/lunhan/xxx/common/orm2/models/SqlParameter.java b/src/main/java/com/lunhan/xxx/common/orm2/models/SqlParameter.java deleted file mode 100644 index 6abf1d7..0000000 --- a/src/main/java/com/lunhan/xxx/common/orm2/models/SqlParameter.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.lunhan.xxx.common.orm2.models; - -public class SqlParameter { - private String name; - private Object value; - /** - * java.sql.Types - */ - private Integer type; - - public SqlParameter(String name, Object value, Integer type) { - this.name = name; - this.value = value; - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Object getValue() { - return value; - } - - public void setValue(Object value) { - this.value = value; - } - - public Integer getType() { - return type; - } - - public void setType(Integer type) { - this.type = type; - } -} diff --git a/src/main/java/com/lunhan/xxx/repository/BasicDao.java b/src/main/java/com/lunhan/xxx/repository/BasicDao.java deleted file mode 100644 index fb67df0..0000000 --- a/src/main/java/com/lunhan/xxx/repository/BasicDao.java +++ /dev/null @@ -1,827 +0,0 @@ -package com.lunhan.xxx.repository; - -import com.lunhan.xxx.common.ConstantFactory; -import com.lunhan.xxx.common.PagerResult; -import com.lunhan.xxx.common.config.SysConfig; -import com.lunhan.xxx.common.enums.ELogger; -import com.lunhan.xxx.common.enums.EResultCode; -import com.lunhan.xxx.common.exceptions.BusinessException; -import com.lunhan.xxx.common.orm2.SqlBuilder; -import com.lunhan.xxx.common.orm2.enums.ColumnBasic; -import com.lunhan.xxx.common.orm2.models.SqlCondition; -import com.lunhan.xxx.common.orm2.models.SqlParameter; -import com.lunhan.xxx.common.util.*; -import com.lunhan.xxx.repository.columns.ETestInfo; -import org.apache.commons.lang3.BooleanUtils; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.transaction.annotation.Transactional; - -import javax.persistence.Column; -import javax.persistence.Id; -import javax.persistence.Table; -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.sql.*; -import java.util.*; -import java.util.stream.Collectors; - -/** - * 数据访问 实现类 - * - * @param <T> 数据实体 - */ -public class BasicDao<T> { - @Autowired - protected JdbcTemplate db; - private Class<T> clazz; - private String tableName; - private ColumnBasic[] columns; - protected List<String> listColumnsName; - protected String allColumnsStr; - - protected static final Logger logger = LoggerUtil.get(ELogger.SQL_LOG); - protected static final Logger sysLogger = LoggerUtil.get(ELogger.SYS_ERROR); - - /** - * 构造方法 - * - * @param columns 数据实体对应的所有列枚举 - */ - public BasicDao(ColumnBasic[] columns) { - this.clazz = (Class<T>) ( - (ParameterizedType) getClass().getGenericSuperclass() - ).getActualTypeArguments()[0]; - this.columns = columns; - this.listColumnsName = Arrays.stream(columns).map(ColumnBasic::getColumnName).collect(Collectors.toList()); - this.allColumnsStr = StringUtil.join(listColumnsName, ","); - - Table annotation = clazz.getAnnotation(Table.class); - if (null == annotation) { - return; - } - this.tableName = annotation.name(); - } - - /** - * 获取数据实体class类型 - * - * @return 数据实体class类型 - */ - public Class<T> getClazz() { - return clazz; - } - - /** - * 获取数据实体对应的所有列枚举 - * - * @return 数据实体对应的所有列枚举 - */ - public ColumnBasic[] getColumns() { - return columns; - } - - /** - * 获取数据库表名 - * - * @return 数据库表名 - */ - public String getTableName() { - return tableName; - } - - /** - * 根据条件获取数据实体列表(不传条件,默认只获取前500条数据) - * - * @return 数据实体列表 - */ - @Transactional(readOnly = true) - protected List<T> getList(SqlBuilder... builder) { - StringBuilder sbSql = new StringBuilder(String.format("SELECT %s FROM %s", allColumnsStr, tableName)); - Object[] params = new Object[0]; - int[] paramTypes = new int[0]; - if (builder.length == 1) { - SqlCondition condition = builder[0].build(); - String where = condition.getSql(); - List<SqlParameter> listParam = condition.getParamList(); - params = new Object[listParam.size()]; - paramTypes = new int[listParam.size()]; - for (int i = 0; i < listParam.size(); i++) { - SqlParameter parameter = listParam.get(i); - params[i] = parameter.getValue(); - paramTypes[i] = parameter.getType(); - } - if (StringUtil.isNotNullOrEmpty(where) && BooleanUtils.isFalse(where.contains("WHERE"))) { - sbSql.append(" WHERE "); - } - sbSql.append(where); - } - sbSql.append(";"); - String sql = sbSql.toString(); - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + StringUtil.join(Arrays.stream(params).map(Object::toString).collect(Collectors.toList()), ConstantFactory.SQL_STR_COMMA) + "]"); - } - List<Map<String, Object>> list = db.queryForList(sql, params, paramTypes); - if (ListUtil.isNullOrEmpty(list)) { - return new ArrayList<>(); - } - List<T> result = new ArrayList<>(); - Field[] fields = clazz.getDeclaredFields(); - for (Map<String, Object> row : list) { - T item = this.fillEntity(fields, row); - if (Objects.isNull(item)) { - continue; - } - result.add(item); - } - return result; - } - - /** - * 根据主键获取数据实体 - * - * @param id 主键id - * @return 数据实体 - */ - @Transactional(readOnly = true) - public T getById(Long id) { - try { - String sql = String.format("SELECT %s FROM %s WHERE id=?", allColumnsStr, tableName); - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + id + "(LONG)" + "]"); - } - Map<String, Object> row = db.queryForMap(sql, new Object[]{id}, new int[]{Types.BIGINT}); - return this.fillEntity(clazz.getDeclaredFields(), row); - } catch (EmptyResultDataAccessException e) { - return null; - } catch (Exception e) { - logger.error("BasicDao.get(Long id)发生异常", e); - throw new BusinessException(EResultCode.ERROR, "BasicDao.get(Long id)发生异常." + e.getMessage()); - } - } - - /** - * 条件查询单个数据实体 - * - * @param builder - * @return - */ - @Transactional(readOnly = true) - protected T get(SqlBuilder builder) { - try { - builder.from(tableName); - StringBuilder sbSql = new StringBuilder(); - SqlCondition conditionFull = builder.build(); - String sqlFull = conditionFull.getSql(); - if (BooleanUtils.isFalse(sqlFull.contains("SELECT"))) { - sbSql.append("SELECT "); - sbSql.append(allColumnsStr); - } - sbSql.append(sqlFull); - List<SqlParameter> listParam = conditionFull.getParamList(); - Object[] params = new Object[listParam.size()]; - int[] paramTypes = new int[listParam.size()]; - for (int i = 0; i < listParam.size(); i++) { - SqlParameter parameter = listParam.get(i); - params[i] = parameter.getValue(); - paramTypes[i] = parameter.getType(); - } - sbSql.append(";"); - String sql = sbSql.toString(); - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + StringUtil.join(Arrays.stream(params).map(Object::toString).collect(Collectors.toList()), ConstantFactory.SQL_STR_COMMA) + "]"); - } - Map<String, Object> row = db.queryForMap(sql, params, paramTypes); - return this.fillEntity(clazz.getDeclaredFields(), row); - } catch (EmptyResultDataAccessException e) { - logger.error("BasicDao.get(SqlBuilder builder)", e); - return null; - } catch (Exception e) { - logger.error("BasicDao.get(SqlBuilder builder)发生异常", e); - throw new BusinessException(EResultCode.ERROR, "BasicDao.get(SqlBuilder builder)发生异常." + e.getMessage()); - } - } - - /** - * 根据传入sql查询数据 - * - * @param sql - * @return - */ - public List<Map<String, Object>> getSql(String sql) { - List<Map<String, Object>> list = db.queryForList(sql); - return list; - } - public Map<String, Object> querySql(String sql){ - Map<String, Object> stringObjectMap = db.queryForMap(sql); - return stringObjectMap; - } - - - /** - * 根据传入sql查询数据 - * - * @param builder sql语句构建器 - */ - public List<Map<String, Object>> getSql(SqlBuilder builder) { - SqlCondition conditionFull = builder.build(); - String sql = conditionFull.getSql(); - - List<SqlParameter> listParam = conditionFull.getParamList(); - Object[] params = new Object[listParam.size()]; - int[] paramTypes = new int[listParam.size()]; - for (int i = 0; i < listParam.size(); i++) { - SqlParameter parameter = listParam.get(i); - params[i] = parameter.getValue(); - paramTypes[i] = parameter.getType(); - } - List<Map<String, Object>> list = db.queryForList(sql, params, paramTypes); - return list; - } - - /** - * 查询总数 - * - * @param sql - * @return - */ - public Integer getCount(String sql) { - return db.queryForObject(sql, Integer.class); - } - - /** - * 根据条件获取数据实体列表(不传条件,默认只获取前500条数据) - * - * @return 数据实体列表 - */ - @Transactional(readOnly = true) - protected PagerResult<T> getPageList(SqlBuilder builder) { - builder.from(tableName); - - StringBuilder sbSql = new StringBuilder(); - Integer pageSize = builder.getPageSize(); - Integer pageIndex = builder.getPageIndex(); - - SqlCondition conditionFull = builder.build(); - String sqlFull = conditionFull.getSql(); - if (BooleanUtils.isFalse(sqlFull.contains("SELECT"))) { - sbSql.append("SELECT "); - sbSql.append(allColumnsStr); - } - sbSql.append(sqlFull); - - List<SqlParameter> listParam = conditionFull.getParamList(); - Object[] params = new Object[listParam.size()]; - int[] paramTypes = new int[listParam.size()]; - for (int i = 0; i < listParam.size(); i++) { - SqlParameter parameter = listParam.get(i); - params[i] = parameter.getValue(); - paramTypes[i] = parameter.getType(); - } - - SqlCondition conditionCount = builder.count(); - String sqlCount = conditionCount.getSql(); - Integer rowCount = db.queryForObject(sqlCount, params, Integer.class); - if (Objects.isNull(rowCount) || rowCount.compareTo(0) < 1) { - return new PagerResult<>(pageSize, pageIndex, 0L, new ArrayList<>()); - } - - sbSql.append(";"); - String sql = sbSql.toString(); - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + StringUtil.join(Arrays.stream(params).map(Object::toString).collect(Collectors.toList()), ConstantFactory.SQL_STR_COMMA) + "]"); - } - List<Map<String, Object>> list = db.queryForList(sql, params, paramTypes); - if (ListUtil.isNullOrEmpty(list)) { - return new PagerResult<>(pageSize, pageIndex, rowCount, new ArrayList<>()); - } - List<T> result = new ArrayList<>(); - Field[] fields = clazz.getDeclaredFields(); - for (Map<String, Object> row : list) { - T item = this.fillEntity(fields, row); - if (Objects.isNull(item)) { - continue; - } - result.add(item); - } - return new PagerResult<>(pageSize, pageIndex, rowCount, result); - } - - /** - * 新增一个数据实体 - * - * @param model 数据实体对象 - * @return 是否成功 - */ - public Boolean add(T model) { - KeyHolder holder = new GeneratedKeyHolder(); - - int rowCount = db.update(new PreparedStatementCreator() { - @Override - public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { - List<Object> listValue = new ArrayList<>(); - List<String> listCol = new ArrayList<>(); - Field[] fields = clazz.getDeclaredFields(); - for (Field field : fields) { - // 要设置属性可达,不然会抛出IllegalAccessException异常 - field.setAccessible(true); - Object value = null; - try { - value = field.get(model); - } catch (IllegalAccessException e) { - continue; - } - if (Objects.isNull(value)) { - continue; - } - Column annotation = field.getAnnotation(Column.class); - if (Objects.isNull(annotation)) { - continue; - } - if (Objects.equals(Boolean.FALSE, annotation.insertable())) { - continue; - } - Id annotationId = field.getAnnotation(Id.class); - if (Objects.nonNull(annotationId)) { - continue; - } - listValue.add(value); - listCol.add(annotation.name()); - } - if (ListUtil.isNullOrEmpty(listValue)) { - throw new RuntimeException("At BasicDao.add, there is no data be insert.The model json: " + SerializeUtil.toJson(model)); - } - String insertColumns = StringUtil.join(listCol, ","); - String valuesPlaceholder = StringUtil.join(listValue.stream().map(c -> "?").collect(Collectors.toList())); - String sql = String.format("INSERT INTO %s(%s) VALUES(%s);", tableName, insertColumns, valuesPlaceholder); - PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - - for (int i = 0; i < listValue.size(); i++) { - //setValue(ps, i + 1, listValue.get(i)); - ps.setObject(i + 1, listValue.get(i), Types.VARCHAR); - } - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + StringUtil.join(listValue.stream().map(c -> c.toString()).collect(Collectors.toList()), ConstantFactory.SQL_STR_COMMA) + "]"); - } - return ps; - } - }, holder); - if (rowCount > 0) { - long id = holder.getKey().longValue(); - Field field = null; - try { - field = clazz.getDeclaredField("id"); - } catch (NoSuchFieldException e) { - sysLogger.error("BasicDao.add(T model)", e); - } - if (Objects.nonNull(field)) { - try { - // 要设置属性可达,不然会抛出IllegalAccessException异常 - field.setAccessible(true); - field.set(model, id); - } catch (IllegalAccessException e) { - sysLogger.error("BasicDao.add(T model)", e); - } - } - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - /** - * 新增一个数据实体(主键非自增列) - * - * @param model 数据实体对象 - * @return 是否成功 - */ - public Boolean addNotIncrement(T model) { - List<Object> listValue = new ArrayList<>(); - List<String> listCol = new ArrayList<>(); - Field[] fields = clazz.getDeclaredFields(); - for (Field field : fields) { - // 要设置属性可达,不然会抛出IllegalAccessException异常 - field.setAccessible(true); - Object value = null; - try { - value = field.get(model); - } catch (IllegalAccessException e) { - continue; - } - if (Objects.isNull(value)) { - continue; - } - Column annotation = field.getAnnotation(Column.class); - if (Objects.isNull(annotation)) { - continue; - } - if (Objects.equals(Boolean.FALSE, annotation.insertable())) { - continue; - } - listValue.add(value); - listCol.add(annotation.name()); - } - if (ListUtil.isNullOrEmpty(listValue)) { - throw new RuntimeException("At BasicDao.addNotIncrement, there is no data be insert.The model json: " + SerializeUtil.toJson(model)); - } - String insertColumns = StringUtil.join(listCol, ","); - String valuesPlaceholder = StringUtil.join(listValue.stream().map(c -> "?").collect(Collectors.toList())); - String sql = String.format("INSERT INTO %s(%s) VALUES(%s);", tableName, insertColumns, valuesPlaceholder); - - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + StringUtil.join(listValue.stream().map(Object::toString).collect(Collectors.toList()), ConstantFactory.SQL_STR_COMMA) + "]"); - } - - try { - int rowCount = db.update(sql, listValue.toArray()); - if (rowCount > 0) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } catch (Exception e) { - logger.error("BasicDao.addNotIncrement(T model)", e); - return Boolean.FALSE; - } - } - - /** - * 根据主键id删除数据实体 - * - * @param id 主键id - * @return 是否成功 - */ - public Boolean remove(Long id) { - String sql = String.format("DELETE FROM %s WHERE id=?;", tableName); - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + id + "(LONG)" + "]"); - } - int rowCount = db.update(sql, id); - if (rowCount > 0) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - /** - * 根据条件删除数据实体 - * - * @param builder 条件 - * @return 是否成功 - */ - protected Boolean remove(SqlBuilder builder) { - SqlCondition build = builder.build(); - String where = build.getSql(); - List<SqlParameter> listParam = build.getParamList(); - String sql = String.format("DELETE FROM %s %s;", tableName, where); - Object[] values = new Object[listParam.size()]; - for (int i = 0; i < listParam.size(); i++) { - SqlParameter p = listParam.get(i); - values[i] = p.getValue(); - } - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + Arrays.toString(values) + "]"); - } - int rowCount = db.update(sql, values); - if (rowCount > 0) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - /** - * 根据主键id逻辑删除数据 - * - * @param id 主键id - * @return 是否成功 - */ - public Boolean deleteLogic(Long id) { - String sql = String.format("UPDATE %s SET is_delete=1 WHERE id=?;", tableName); - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + id + "(INTEGER)" + "]"); - } - int rowCount = db.update(sql, id); - if (rowCount > 0) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - /** - * 根据条件逻辑删除数据 - * - * @param listId id列表 - * @return 是否成功 - */ - public Boolean deleteLogic(List<Long> listId) { - SqlCondition build = new SqlBuilder().where(ETestInfo.ID.in(listId)).build(); - String where = build.getSql(); - List<SqlParameter> listParam = build.getParamList(); - String sql = String.format("UPDATE %s SET is_delete=1 %s;", tableName, where); - Object[] values = new Object[listParam.size()]; - for (int i = 0; i < listParam.size(); i++) { - SqlParameter p = listParam.get(i); - values[i] = p.getValue(); - } - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + Arrays.toString(values) + "]"); - } - int rowCount = db.update(sql, values); - if (rowCount > 0) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - /** - * 修改一个数据实体 - * - * @param model 数据实体对象 - * @return 是否成功 - */ - public Boolean modify(T model) { - List<Object> listValue = new ArrayList<>(); - List<String> listSet = new ArrayList<>(); - Field[] fields = clazz.getDeclaredFields(); - - String idColumnName = ""; - Object idValue = null; - for (Field field : fields) { - // 要设置属性可达,不然会抛出IllegalAccessException异常 - field.setAccessible(true); - Object value = null; - try { - value = field.get(model); - } catch (IllegalAccessException e) { - continue; - } - if (Objects.isNull(value)) { - continue; - } - Column annotation = field.getAnnotation(Column.class); - if (Objects.isNull(annotation)) { - continue; - } - if (Objects.equals(Boolean.FALSE, annotation.updatable())) { - continue; - } - Id annotationId = field.getAnnotation(Id.class); - if (Objects.nonNull(annotationId)) { - idColumnName = annotation.name(); - idValue = value; - if (NumericUtil.tryParseLong(idValue).compareTo(0L) < 1) { - throw new RuntimeException("At BasicDao.modify, the value of “id” is must.The model json: " + SerializeUtil.toJson(model)); - } - continue; - } - listValue.add(value); - listSet.add(annotation.name() + "=?"); - } - if (ListUtil.isNullOrEmpty(listValue)) { - throw new RuntimeException("At BasicDao.modify, there is no data be update.The model json: " + SerializeUtil.toJson(model)); - } - String sql = String.format("UPDATE %s SET %s WHERE %s =?;", tableName, StringUtil.join(listSet, ","), idColumnName); - // 添加sql参数 id的值 - listValue.add(idValue); - - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + StringUtil.join(listValue.stream().map(Object::toString).collect(Collectors.toList()), ConstantFactory.SQL_STR_COMMA) + "]"); - } - int rowCount = db.update(sql, listValue.toArray()); - if (rowCount > 0) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - /** - * 批量新增数据实体 - * - * @param list 数据实体对象列表 - * @return 是否成功 - */ - public Boolean addList(List<T> list) { - if (ListUtil.isNullOrEmpty(list)) { - return Boolean.TRUE; - } - - List<Object[]> listValue = new ArrayList<>(); - List<String> listCol = new ArrayList<>(); - Field[] fields = clazz.getDeclaredFields(); - for (int i = 0; i < list.size(); i++) { - T model = list.get(i); - List<Object> values = new ArrayList<>(); - for (int j = 0; j < fields.length; j++) { - Field field = fields[j]; - // 要设置属性可达,不然会抛出IllegalAccessException异常 - field.setAccessible(true); - Object value = null; - try { - value = field.get(model); - } catch (IllegalAccessException e) { - continue; - } - if (Objects.isNull(value)) { - continue; - } - Column annotation = field.getAnnotation(Column.class); - if (Objects.isNull(annotation)) { - continue; - } - if (Objects.equals(Boolean.FALSE, annotation.insertable())) { - continue; - } - if (0 == i) { - listCol.add(annotation.name()); - } - values.add(value); - } - listValue.add(values.toArray()); - } - if (ListUtil.isNullOrEmpty(listCol)) { - throw new RuntimeException("At BasicDao.addList, there is no data be update.The list json: " + SerializeUtil.toJson(list)); - } - String valuesPlaceholder = StringUtil.join(listCol.stream().map(c -> "?").collect(Collectors.toList())); - String sql = String.format("INSERT INTO %s(%s) VALUES(%s);", tableName, StringUtil.join(listCol, ","), valuesPlaceholder); - - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + StringUtil.join(listValue.stream().map(Object::toString).collect(Collectors.toList()), ConstantFactory.SQL_STR_COMMA) + "]"); - } - int[] batchUpdate = db.batchUpdate(sql, listValue); - if (batchUpdate.length > 0) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - /** - * 批量新增数据实体 - * - * @param list 数据实体对象列表 - * @return 是否成功 - */ - public Boolean modifyList(List<T> list) { - if (ListUtil.isNullOrEmpty(list)) { - return Boolean.TRUE; - } - - List<Object[]> listValue = new ArrayList<>(); - List<String> listSet = new ArrayList<>(); - Field[] fields = clazz.getDeclaredFields(); - for (int i = 0; i < list.size(); i++) { - T model = list.get(i); - List<Object> values = new ArrayList<>(); - - Field idField = null; - for (int j = 0; j < fields.length; j++) { - Field field = fields[j]; - // 要设置属性可达,不然会抛出IllegalAccessException异常 - field.setAccessible(true); - Object value = null; - try { - value = field.get(model); - } catch (IllegalAccessException e) { - continue; - } - if (Objects.isNull(value)) { - continue; - } - Column annotation = field.getAnnotation(Column.class); - if (Objects.isNull(annotation)) { - continue; - } - if (Objects.equals(Boolean.FALSE, annotation.updatable())) { - continue; - } - Id annotationId = field.getAnnotation(Id.class); - if (Objects.nonNull(annotationId)) { - idField = field; - continue; - } - if (0 == i) { - listSet.add(annotation.name() + "=?"); - } - values.add(value); - } - if (Objects.isNull(idField)) { - throw new RuntimeException("At BasicDao.modifyList, the value of “id” is must.The model json: " + SerializeUtil.toJson(model)); - } - try { - // 要设置属性可达,不然会抛出IllegalAccessException异常 - idField.setAccessible(true); - // 设置参数“id”的值 - Object id = idField.get(model); - if (NumericUtil.tryParseLong(id).compareTo(0L) < 1) { - throw new RuntimeException("At BasicDao.modifyList, the value of “id” is must.The model json: " + SerializeUtil.toJson(model)); - } - values.add(id); - } catch (IllegalAccessException e) { - sysLogger.error("BasicDao.modifyList", e); - } - listValue.add(values.toArray()); - } - if (ListUtil.isNullOrEmpty(listSet)) { - throw new RuntimeException("At BasicDao.addList, there is no data be update.The list json: " + SerializeUtil.toJson(list)); - } - String valuesPlaceholder = StringUtil.join(listSet.stream().map(c -> "?").collect(Collectors.toList())); - String sql = String.format("UPDATE %s SET %s WHERE id=?;", tableName, StringUtil.join(listSet, ",")); - - if (SysConfig.isSqlLog()) { - logger.info(sql + "\n[" + StringUtil.join(listValue.stream().map(Object::toString).collect(Collectors.toList()), ConstantFactory.SQL_STR_COMMA) + "]"); - } - int[] batchUpdate = db.batchUpdate(sql, listValue); - if (batchUpdate.length > 0) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - - /** - * 将查询得到的字段键值对封装为数据实体 - * - * @param fields 数据实体的字段列表 - * @param row 查询得到的字段键值对 - * @return 数据实体 - */ - protected T fillEntity(Field[] fields, Map<String, Object> row) { - T item = null; - try { - item = clazz.newInstance(); - } catch (Exception e) { - sysLogger.error("BasicDao.fillEntity", e); - } - if (null == item) { - return null; - } - for (Map.Entry<String, Object> column : row.entrySet()) { - String columnName = column.getKey(); - Field field = Arrays.stream(fields) - .filter(c -> { - Column annotation = c.getAnnotation(Column.class); - if (null == annotation) { - return Boolean.FALSE; - } - return Objects.equals(annotation.name(), columnName); - }) - .findAny().orElse(null); - if (null == field) { - continue; - } - // 要设置属性可达,不然会抛出IllegalAccessException异常 - field.setAccessible(true); - try { - field.set(item, column.getValue()); - } catch (IllegalAccessException e) { - sysLogger.error("BasicDao.fillEntity(Field[] fields, Map<String, Object> row)", e); - } - } - return item; - } - - /** - * 将查询得到的字段键值对封装为数据实体 - * - * @param clazz 数据实体的class类型 - * @param row 查询得到的字段键值对 - * @return 数据实体 - */ - protected <M> M fillEntity(Class<M> clazz, Map<String, Object> row) { - M item = null; - try { - item = clazz.newInstance(); - } catch (Exception e) { - sysLogger.error("BasicDao.fillEntity", e); - } - if (null == item) { - return null; - } - Field[] fields = clazz.getDeclaredFields(); - for (Map.Entry<String, Object> column : row.entrySet()) { - String columnName = column.getKey(); - Field field = Arrays.stream(fields) - .filter(c -> { - Column annotation = c.getAnnotation(Column.class); - if (null == annotation) { - return Boolean.FALSE; - } - return Objects.equals(annotation.name(), columnName); - }) - .findAny().orElse(null); - if (null == field) { - continue; - } - // 要设置属性可达,不然会抛出IllegalAccessException异常 - field.setAccessible(true); - try { - field.set(item, column.getValue()); - } catch (IllegalAccessException e) { - sysLogger.error("BasicDao.fillEntity(Class<M> clazz, Map<String, Object> row)", e); - } - } - return item; - } -} diff --git a/src/main/java/com/lunhan/xxx/repository/BasicMapper.java b/src/main/java/com/lunhan/xxx/repository/BasicMapper.java new file mode 100644 index 0000000..f780ff6 --- /dev/null +++ b/src/main/java/com/lunhan/xxx/repository/BasicMapper.java @@ -0,0 +1,4 @@ +package com.lunhan.xxx.repository; + +public interface BasicMapper { +} diff --git a/src/main/java/com/lunhan/xxx/repository/BasicMapperImpl.java b/src/main/java/com/lunhan/xxx/repository/BasicMapperImpl.java new file mode 100644 index 0000000..8c28141 --- /dev/null +++ b/src/main/java/com/lunhan/xxx/repository/BasicMapperImpl.java @@ -0,0 +1,260 @@ +package com.lunhan.xxx.repository; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.lunhan.xxx.common.enums.ELogger; +import com.lunhan.xxx.common.enums.EResultCode; +import com.lunhan.xxx.common.enums.EYesOrNo; +import com.lunhan.xxx.common.exceptions.BusinessException; +import com.lunhan.xxx.common.util.LoggerUtil; +import org.apache.ibatis.session.ResultHandler; +import org.slf4j.Logger; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.Table; +import java.io.Serializable; +import java.lang.reflect.ParameterizedType; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * 数据访问 实现类 + * + * @param <T> 数据实体 + */ +public class BasicMapper<T> { + protected BaseMapper<T> DB; + protected Class<T> clazz; + protected String tableName; + + protected static final Logger logger = LoggerUtil.get(ELogger.SQL_LOG); + + /** + * 构造方法 + */ + public BasicMapper(BaseMapper<T> db) { + this.clazz = (Class<T>) ( + (ParameterizedType) getClass().getGenericSuperclass() + ).getActualTypeArguments()[0]; + this.DB = db; + Table annotation = clazz.getAnnotation(Table.class); + if (null == annotation) { + return; + } + this.tableName = annotation.name(); + } + + public LambdaQueryWrapper<T> query() { + return Wrappers.lambdaQuery(); + } + + public UpdateWrapper<T> update() { + return Wrappers.update(); + } + + public int insert(T entity) { + return DB.insert(entity); + } + + public int deleteById(T entity) { + return DB.deleteById(entity); + } + + public int delete(Wrapper<T> queryWrapper) { + return DB.delete(queryWrapper); + } + + public int updateById(T entity) { + return DB.updateById(entity); + } + + public int update(T entity, Wrapper<T> updateWrapper) { + return DB.update(entity, updateWrapper); + } + + public T selectById(Serializable id) { + return DB.selectById(id); + } + + public List<T> selectBatchIds(Collection<? extends Serializable> idList) { + return DB.selectBatchIds(idList); + } + + public void selectBatchIds(Collection<? extends Serializable> idList, ResultHandler<T> resultHandler) { + DB.selectBatchIds(idList, resultHandler); + } + + public Long selectCount(Wrapper<T> queryWrapper) { + return DB.selectCount(queryWrapper); + } + + public List<T> selectList(Wrapper<T> queryWrapper) { + return DB.selectList(queryWrapper); + } + + public void selectList(Wrapper<T> queryWrapper, ResultHandler<T> resultHandler) { + DB.selectList(queryWrapper, resultHandler); + } + + public List<T> selectList(IPage<T> page, Wrapper<T> queryWrapper) { + return DB.selectList(page, queryWrapper); + } + + public void selectList(IPage<T> page, Wrapper<T> queryWrapper, ResultHandler<T> resultHandler) { + DB.selectList(page, queryWrapper, resultHandler); + } + + public List<Map<String, Object>> selectMaps(Wrapper<T> queryWrapper) { + return DB.selectMaps(queryWrapper); + } + + public void selectMaps(Wrapper<T> queryWrapper, ResultHandler<Map<String, Object>> resultHandler) { + DB.selectMaps(queryWrapper, resultHandler); + } + + public List<Map<String, Object>> selectMaps(IPage<? extends Map<String, Object>> page, Wrapper<T> queryWrapper) { + return DB.selectMaps(page, queryWrapper); + } + + public void selectMaps(IPage<? extends Map<String, Object>> page, Wrapper<T> queryWrapper, ResultHandler<Map<String, Object>> resultHandler) { + DB.selectMaps(page, queryWrapper, resultHandler); + } + + public <E> List<E> selectListObject(Wrapper<T> queryWrapper) { + return DB.selectObjs(queryWrapper); + } + + public <E> void selectListObject(Wrapper<T> queryWrapper, ResultHandler<E> resultHandler) { + DB.selectObjs(queryWrapper, resultHandler); + } + + /** + * 根据条件获取数据实体列表 + * + * @param queryWrapper 查询条件 + */ + @Transactional(readOnly = true) + protected List<T> getList(Wrapper<T>... queryWrapper) { + return DB.selectList(queryWrapper.length > 0 ? queryWrapper[0] : null); + } + + /** + * 条件查询单个数据实体 + * + * @param queryWrapper 查询条件 + */ + @Transactional(readOnly = true) + protected T get(Wrapper<T> queryWrapper) { + String method = "BasicDao.Wrapper<T> queryWrapper"; + try { + return DB.selectOne(queryWrapper); + } catch (EmptyResultDataAccessException e) { + logger.error(method, e); + return null; + } catch (Exception e) { + logger.error(method + ", 发生异常", e); + throw new BusinessException(EResultCode.ERROR, "BasicDao.get(SqlBuilder builder)发生异常." + e.getMessage()); + } + } + + + /** + * 根据传入sql查询数据 + * + * @param queryWrapper 查询条件 + */ + public List<Map<String, Object>> getMap(Wrapper<T> queryWrapper) { + return DB.selectMaps(queryWrapper); + } + + /** + * 查询记录条数 + * + * @param queryWrapper 查询条件 + */ + public Long getCount(Wrapper<T> queryWrapper) { + return DB.selectCount(queryWrapper); + } + + /** + * 根据主键id删除数据 + * + * @param id 主键id + * @return 是否成功 + */ + public Boolean remove(Long id) { + int rowCount = DB.deleteById(id); + if (rowCount > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + /** + * 根据主键id删除数据 + * + * @param listId id列表 + * @return 是否成功 + */ + public Boolean remove(List<Long> listId) { + int rowCount = DB.deleteByIds(listId); + if (rowCount > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + + } + + /** + * 根据条件删除数据 + * + * @param queryWrapper 查询条件 + */ + protected Boolean remove(Wrapper<T> queryWrapper) { + int rowCount = DB.delete(queryWrapper); + if (rowCount > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + /** + * 根据主键id逻辑删除数据(逻辑删除) + * + * @param id 主键id + * @return 是否成功 + */ + public Boolean deleteLogic(Long id) { + UpdateWrapper<T> where = Wrappers.update(); + where.set("is_delete", EYesOrNo.YES.getValue()); + where.eq("id", id); + int rowCount = DB.update(where); + if (rowCount > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + /** + * 根据逐渐删除数据(逻辑删除) + * + * @param listId id列表 + * @return 是否成功 + */ + public Boolean deleteLogic(List<Long> listId) { + UpdateWrapper<T> where = Wrappers.update(); + where.set("is_delete", EYesOrNo.YES.getValue()); + where.in("id", listId); + int rowCount = DB.update(where); + if (rowCount > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } +} diff --git a/src/main/java/com/lunhan/xxx/repository/BasicPO.java b/src/main/java/com/lunhan/xxx/repository/BasicPO.java new file mode 100644 index 0000000..6b22f13 --- /dev/null +++ b/src/main/java/com/lunhan/xxx/repository/BasicPO.java @@ -0,0 +1,6 @@ +package com.lunhan.xxx.repository; + +import java.io.Serializable; + +public class BaiscDao implements Serializable { +} diff --git a/src/main/java/com/lunhan/xxx/repository/DaoConfig.java b/src/main/java/com/lunhan/xxx/repository/DaoConfig.java deleted file mode 100644 index fc9a6f2..0000000 --- a/src/main/java/com/lunhan/xxx/repository/DaoConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.lunhan.xxx.repository; - -import com.lunhan.xxx.common.orm2.enums.ColumnBasic; -import com.lunhan.xxx.repository.columns.*; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; - - -public class DaoConfig { - public static final Map<String, Class<?>> TYPES_4_TABLE = new HashMap<String, Class<?>>() {{ - put("test_info", ETestInfo.class); - }}; - - public static final Map<String, Map<String, ColumnBasic>> COLUMNS_4_TABLE = new HashMap<String, Map<String, ColumnBasic>>() {{ - put("test_info", Arrays.stream(ETestInfo.values()).collect(Collectors.toMap(ColumnBasic::getColumnName, c -> c))); - }}; -} diff --git a/src/main/java/com/lunhan/xxx/repository/columns/ETestInfo.java b/src/main/java/com/lunhan/xxx/repository/columns/ETestInfo.java deleted file mode 100644 index 42c0505..0000000 --- a/src/main/java/com/lunhan/xxx/repository/columns/ETestInfo.java +++ /dev/null @@ -1,119 +0,0 @@ -/** -# __----~~~~~~~~~~~------___ -# . . ~~//====...... __--~ ~~ -# -. \_|// |||\\ ~~~~~~::::... /~ -# ___-==_ _-~o~ \/ ||| \\ _/~~- -# __---~~~.==~||\=_ -_--~/_-~|- |\\ \\ _/~ -# _-~~ .=~ | \\-_ '-~7 /- / || \ / -# .~ .~ | \\ -_ / /- / || \ / -# / ____ / | \\ ~-_/ /|- _/ .|| \ / -# |~~ ~~|--~~~~--_ \ ~==-/ | \~--===~~ .\ -# ' ~-| /| |-~\~~ __--~~ -# |-~~-_/ | | ~\_ _-~ /\ -# / \ \__ \/~ \__ -# _--~ _/ | .-~~____--~-/ ~~==. -# ((->/~ '.|||' -_| ~~-/ , . _|| -# -_ ~\ ~~---l__i__i__i--~~_/ -# _-~-__ ~) \--______________--~~ -# //.-~~~-~_--~- |-------~~~~~~~~ -# //.-~~~--\ -# 神兽保佑 -# 永无BUG! -*/ -package com.lunhan.xxx.repository.columns; - -import com.lunhan.xxx.common.orm2.enums.ColumnBasic; - -import java.util.Arrays; -import java.util.Objects; - -/** - * 测试信息 字段枚举 - * @author lin.liu - * @description 测试信息 字段枚举 - * @date 2021/11/23 - */ -public enum ETestInfo implements ColumnBasic { - - /** - * 自增id - */ - ID("id", 1), - /** - * 名称 - */ - NAME("name", 1), - /** - * 用户id - */ - USER_ID("user_id", 1), - /** - * 电话 - */ - PHONE("phone", 1), - /** - * 余额 - */ - BALANCE("balance", 1), - /** - * 性别 男=1,女=2,其他=3 - */ - SEX("sex", 1), - /** - * 生日 - */ - BIRTHDAY("birthday", 1), - /** - * 排序值 - */ - SORT("sort", 1), - /** - * 状态 正常=200,停用=300,删除=400 - */ - STATUS("status", 1), - /** - * 备注 - */ - COMMENT("comment", 1), - /** - * 创建时间 - */ - CREATE_TIME("create_time", 1), - /** - * 数据最后更新时间 - */ - UPDATE_TIME("update_time", 1); - - private String columnName; - private Integer value; - public Integer getValue() { - return value; - } - public String getColumnName() { - return columnName; - } - static final String TABLE_NAME = "test_info"; - public String getTableName() { - return TABLE_NAME; - } - - ETestInfo(String columnName, Integer value) { - this.columnName = columnName; - this.value = value; - } - - public static ETestInfo getByValue(Integer value) { - return Arrays.stream(ETestInfo.values()) - .filter(e -> Objects.equals(e.getValue(), value)) - .findAny() - .orElse(null); - } - - @Override - public String toString() { - return "ETestInfo{" + - "columnName='" + columnName + '\'' + - ", value=" + value + - '}'; - } -} diff --git a/src/main/java/com/lunhan/xxx/repository/dao/TestInfoDao.java b/src/main/java/com/lunhan/xxx/repository/dao/TestInfoDao.java deleted file mode 100644 index 5f362e7..0000000 --- a/src/main/java/com/lunhan/xxx/repository/dao/TestInfoDao.java +++ /dev/null @@ -1,123 +0,0 @@ -/** -# __----~~~~~~~~~~~------___ -# . . ~~//====...... __--~ ~~ -# -. \_|// |||\\ ~~~~~~::::... /~ -# ___-==_ _-~o~ \/ ||| \\ _/~~- -# __---~~~.==~||\=_ -_--~/_-~|- |\\ \\ _/~ -# _-~~ .=~ | \\-_ '-~7 /- / || \ / -# .~ .~ | \\ -_ / /- / || \ / -# / ____ / | \\ ~-_/ /|- _/ .|| \ / -# |~~ ~~|--~~~~--_ \ ~==-/ | \~--===~~ .\ -# ' ~-| /| |-~\~~ __--~~ -# |-~~-_/ | | ~\_ _-~ /\ -# / \ \__ \/~ \__ -# _--~ _/ | .-~~____--~-/ ~~==. -# ((->/~ '.|||' -_| ~~-/ , . _|| -# -_ ~\ ~~---l__i__i__i--~~_/ -# _-~-__ ~) \--______________--~~ -# //.-~~~-~_--~- |-------~~~~~~~~ -# //.-~~~--\ -# 神兽保佑 -# 永无BUG! -*/ -package com.lunhan.xxx.repository.dao; - -import com.lunhan.xxx.common.ConstantFactory; -import com.lunhan.xxx.common.PagerResult; -import com.lunhan.xxx.common.orm2.SqlBuilder; -import com.lunhan.xxx.common.util.ListUtil; -import com.lunhan.xxx.common.util.NumericUtil; -import com.lunhan.xxx.common.util.StringUtil; -import com.lunhan.xxx.entity.dto.OrderByDTO; -import com.lunhan.xxx.entity.dto.search.SearchTestInfo; -import com.lunhan.xxx.entity.enums.EOrderBy; -import com.lunhan.xxx.entity.enums.EState; -import com.lunhan.xxx.repository.BasicDao; -import com.lunhan.xxx.repository.columns.ETestInfo; -import com.lunhan.xxx.repository.po.TestInfoPO; -import org.springframework.stereotype.Repository; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * 测试信息 数据访问类 - * @author lin.liu - * @description 测试信息 数据访问类 - * @date 2021/11/23 - */ - -@Repository -public class TestInfoDao extends BasicDao<TestInfoPO> { - TestInfoDao() { - super(ETestInfo.values()); - } - - public Boolean removeByListId(List<Long> listId) { - return super.remove(new SqlBuilder().where(ETestInfo.ID.in(listId))); - } - - public PagerResult<TestInfoPO> search(SearchTestInfo search) { - SqlBuilder builder = new SqlBuilder() - // 分页参数 - .page(NumericUtil.tryParseInt(search.getPage(), 1), NumericUtil.tryParseInt(search.getLimit(), 1)) - - // 状态 != 400 - .and(ETestInfo.STATUS.notEqual(EState.DELETED.getValue())) - // 状态 - .andIf(NumericUtil.tryParseInt(search.getStatus()).compareTo(0) > 0, ETestInfo.STATUS.equal(search.getStatus())) - // 状态列表 - .andIf(ListUtil.isNotNullOrEmpty(search.getListStatus()), ETestInfo.STATUS.in(search.getListStatus())) - // id列表 - .andIf(ListUtil.isNotNullOrEmpty(search.getListId()), ETestInfo.ID.in(search.getListId())) - // 关键字 - .andIf(StringUtil.isNotNullOrEmpty(search.getKeywords()), ETestInfo.NAME.like(search.getKeywords())) - // 创建时间-起始 - .andIf(NumericUtil.tryParseLong(search.getCreateTimeStart()).compareTo(0L) > 0, ETestInfo.CREATE_TIME.greaterOrEqual(search.getCreateTimeStart())) - // 创建时间-截止 - .andIf(NumericUtil.tryParseLong(search.getCreateTimeEnd()).compareTo(0L) > 0, ETestInfo.CREATE_TIME.lessOrEqual(search.getCreateTimeEnd())) - ; - - - if (ListUtil.isNotNullOrEmpty(search.getOrderBy())) { - List<String> listOrderBy = new ArrayList<>(); - for (OrderByDTO item : search.getOrderBy()) { - EOrderBy orderBy = EOrderBy.getByValue(NumericUtil.tryParseInt(item.getOrderBy(), 1)); - if (Objects.isNull(orderBy)) { - continue; - } - switch (orderBy) { - case ID: - listOrderBy.add(ETestInfo.ID.getColumnName() + - (item.getIsAsc() ? ConstantFactory.SQL_ASC : ConstantFactory.SQL_DESC) - ); - break; - - case CREATE_TIME: - listOrderBy.add(ETestInfo.CREATE_TIME.getColumnName() + - (item.getIsAsc() ? ConstantFactory.SQL_ASC : ConstantFactory.SQL_DESC) - ); - break; - - case UPDATE_TIME: - listOrderBy.add(ETestInfo.UPDATE_TIME.getColumnName() + - (item.getIsAsc() ? ConstantFactory.SQL_ASC : ConstantFactory.SQL_DESC) - ); - break; - - default: - break; - } - } - builder.orderBy(ListUtil.toArray(listOrderBy)); - } - return super.getPageList(builder); - } - - public List<TestInfoPO> getListById(List<Long> listId) { - return super.getList(new SqlBuilder() - .where(ETestInfo.ID.in(listId)) - ); - } -} diff --git a/src/main/java/com/lunhan/xxx/repository/imapper/TestInfoMapper.java b/src/main/java/com/lunhan/xxx/repository/imapper/TestInfoMapper.java new file mode 100644 index 0000000..d11044a --- /dev/null +++ b/src/main/java/com/lunhan/xxx/repository/imapper/TestInfoMapper.java @@ -0,0 +1,4 @@ +package com.lunhan.xxx.repository.imapper; + +public interface TestInfoMapper { +} diff --git a/src/main/java/com/lunhan/xxx/repository/mapper/TestInfoMapperImpl.java b/src/main/java/com/lunhan/xxx/repository/mapper/TestInfoMapperImpl.java new file mode 100644 index 0000000..5117fc7 --- /dev/null +++ b/src/main/java/com/lunhan/xxx/repository/mapper/TestInfoMapperImpl.java @@ -0,0 +1,127 @@ +/** +# __----~~~~~~~~~~~------___ +# . . ~~//====...... __--~ ~~ +# -. \_|// |||\\ ~~~~~~::::... /~ +# ___-==_ _-~o~ \/ ||| \\ _/~~- +# __---~~~.==~||\=_ -_--~/_-~|- |\\ \\ _/~ +# _-~~ .=~ | \\-_ '-~7 /- / || \ / +# .~ .~ | \\ -_ / /- / || \ / +# / ____ / | \\ ~-_/ /|- _/ .|| \ / +# |~~ ~~|--~~~~--_ \ ~==-/ | \~--===~~ .\ +# ' ~-| /| |-~\~~ __--~~ +# |-~~-_/ | | ~\_ _-~ /\ +# / \ \__ \/~ \__ +# _--~ _/ | .-~~____--~-/ ~~==. +# ((->/~ '.|||' -_| ~~-/ , . _|| +# -_ ~\ ~~---l__i__i__i--~~_/ +# _-~-__ ~) \--______________--~~ +# //.-~~~-~_--~- |-------~~~~~~~~ +# //.-~~~--\ +# 神兽保佑 +# 永无BUG! +*/ +package com.lunhan.xxx.repository.dao; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.lunhan.xxx.common.PagerResult; +import com.lunhan.xxx.common.enums.EYesOrNo; +import com.lunhan.xxx.common.util.ListUtil; +import com.lunhan.xxx.common.util.NumericUtil; +import com.lunhan.xxx.common.util.StringUtil; +import com.lunhan.xxx.entity.dto.OrderByDTO; +import com.lunhan.xxx.entity.dto.search.SearchTestInfo; +import com.lunhan.xxx.entity.enums.EOrderBy; +import com.lunhan.xxx.repository.BasicDao; +import com.lunhan.xxx.repository.po.TestInfoPO; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * 测试信息 数据访问类 + * @author lin.liu + * @description 测试信息 数据访问类 + * @date 2021/11/23 + */ + +@Repository +public class TestInfoDao extends BasicDao<TestInfoPO> { +// TestInfoDao() { +// super(ETestInfo.values()); +// } + + public Boolean removeByListId(List<Long> listId) { + return super.deleteLogic(listId); + } + + public PagerResult<TestInfoPO> search(SearchTestInfo search) { + // 查询条件 + LambdaQueryWrapper<TestInfoPO> queryWrapper = this.query(); + // 非逻辑删除 + queryWrapper.eq(TestInfoPO::getIsDelete, EYesOrNo.NO.getValue()); + // 状态 + queryWrapper.eq(NumericUtil.tryParseInt(search.getStatus()).compareTo(0) > 0, TestInfoPO::getStatus, search.getStatus()); + // 状态列表 + queryWrapper.in(ListUtil.isNotNullOrEmpty(search.getListStatus()), TestInfoPO::getStatus, search.getListStatus()); + + // 数据创建时间-起始 + queryWrapper.ge(NumericUtil.tryParseLong(search.getCreateTimeStart()).compareTo(0L) > 0, TestInfoPO::getCreateTime, search.getCreateTimeStart()); + // 数据创建时间-截止 + queryWrapper.le(NumericUtil.tryParseLong(search.getCreateTimeEnd()).compareTo(0L) > 0, TestInfoPO::getCreateTime, search.getCreateTimeEnd()); + // 关键字 + if (StringUtil.isNotNullOrEmpty(search.getKeywords())) { + queryWrapper.and(q -> + q.like(TestInfoPO::getName, search.getKeywords()) + .or().like(TestInfoPO::getPhone, search.getKeywords()) + ); + } + + // 排序处理 + if (ListUtil.isNotNullOrEmpty(search.getOrderBy())) { + for (OrderByDTO item : search.getOrderBy()) { + EOrderBy orderBy = EOrderBy.getByValue(item.getOrderBy()); + // 顺序排序 + if (item.getIsAsc()) { + switch (orderBy) { + // 主键 + case ID: + queryWrapper.orderByAsc(TestInfoPO::getId); + break; + // 数据创建时间 + case CREATE_TIME: + queryWrapper.orderByAsc(TestInfoPO::getCreateTime); + break; + // 最后更新时间 + case UPDATE_TIME: + queryWrapper.orderByAsc(TestInfoPO::getUpdateTime); + break; + } + } else { + // 倒叙排序 + switch (orderBy) { + // 主键 + case ID: + queryWrapper.orderByAsc(TestInfoPO::getId); + break; + // 数据创建时间 + case CREATE_TIME: + queryWrapper.orderByAsc(TestInfoPO::getCreateTime); + break; + // 最后更新时间 + case UPDATE_TIME: + queryWrapper.orderByAsc(TestInfoPO::getUpdateTime); + break; + } + } + } + } else { + queryWrapper.orderByDesc(TestInfoPO::getId); + } + return super.getPageList(new Page<>(search.getPage(), search.getLimit()), queryWrapper); + } + + public List<TestInfoPO> getListById(List<Long> listId) { + return super.db.selectBatchIds(listId); + } +} diff --git a/src/main/java/com/lunhan/xxx/service/convert/TestInfoMapper.java b/src/main/java/com/lunhan/xxx/service/convert/TestInfoConvert.java similarity index 100% rename from src/main/java/com/lunhan/xxx/service/convert/TestInfoMapper.java rename to src/main/java/com/lunhan/xxx/service/convert/TestInfoConvert.java diff --git a/src/test/java/com/lunhan/xxx/host/GenCodeMySQL.java b/src/test/java/com/lunhan/xxx/host/GenCodeMySQL.java deleted file mode 100644 index 8441458..0000000 --- a/src/test/java/com/lunhan/xxx/host/GenCodeMySQL.java +++ /dev/null @@ -1,1939 +0,0 @@ -package com.lunhan.xxx.host; - -import com.lunhan.xxx.common.ConstantFactory; -import com.lunhan.xxx.common.util.ListUtil; -import com.lunhan.xxx.common.util.LocalDateTimeUtil; -import com.lunhan.xxx.common.util.NumericUtil; -import com.lunhan.xxx.common.util.StringUtil; -import org.apache.commons.lang3.BooleanUtils; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.sql.*; -import java.util.*; - -public class GenCodeMySQL { - private static final String HOST = "192.168.0.100"; - private static final String PORT = "57654"; - private static final String USER = "lunhan"; - private static final String PASSWORD = "lunhan.20240330"; - private static final String DB_NAME = "water_trade_center"; - private static final String AUTHOR = "zr"; - - private static Connection CONN = null; - private static final String DRIVER = "org.postgresql.Driver"; - private static final String CONNECTION_STR = "jdbc:postgresql://" + HOST + ":" + PORT + "/" + DB_NAME; - - //region 输出文件路径设置 - class OutSet { - public static final String PO = "./src/main/java/com/lunhan/water/repository/po/"; - public static final String VO = "./src/main/java/com/lunhan/water/repository/vo/"; - public static final String COMVERT_MAPPER = "./src/main/java/com/lunhan/water/service/convert/"; - public static final String COLUMNS_ENUM = "./src/main/java/com/lunhan/water/repository/columns/"; - public static final String DAO = "./src/main/java/com/lunhan/water/repository/dao/"; - public static final String MAPPER = "./src/main/java/com/lunhan/water/repository/"; - public static final String MAPPERXML = "./src/main/resources/mapper/"; - public static final String SERVICE = "./src/main/java/com/lunhan/water/service/"; - public static final String Controller = "./src/main/java/com/lunhan/water/host/controller/"; - public static final String SEARCH = "./src/main/java/com/lunhan/water/entity/dto/search/"; - public static final String RequestDTO = "./src/main/java/com/lunhan/water/entity/request/"; - public static final String ResponseDTO = "./src/main/java/com/lunhan/water/entity/response/"; - } - //endregion - - //region 架包路径设置 - class PackageSet { - public static final String PO = "com.lunhan.xxx.repository.po"; - public static final String VO = "com.lunhan.xxx.repository.vo"; - public static final String CONVERT_MAPPER = "com.lunhan.xxx.service.convert"; - public static final String DAO = "com.lunhan.xxx.repository.dao"; - public static final String COLUMNS_ENUM = "com.lunhan.xxx.repository.columns"; - public static final String MAPPER = "com.lunhan.xxx.repository"; - public static final String SERVICE = "com.lunhan.xxx.service"; - public static final String Controller = "com.lunhan.xxx.host.controller"; - public static final String SEARCH = "com.lunhan.xxx.entity.dto.search"; - public static final String Request = "com.lunhan.xxx.entity.request"; - public static final String Response = "com.lunhan.xxx.entity.response"; - } - //endregion - - //region 后缀名设置 - class SuffixSet { - public static final String PO = "PO"; - public static final String VO = "VO"; - public static final String COLUMNS_ENUM = "";//POColumns - public static final String DAO = "Dao"; - public static final String MAPPER = "Mapper"; - public static final String SERVICE = "Service"; - public static final String Controller = "Controller"; - public static final String Request = "Req"; - public static final String Response = "Res"; - public static final String Create = "ReqCreate"; - public static final String Modify = "ReqModify"; - } - //endregion - - //region po中getter/setter生成方式设置 - /** - * po中getter/setter生成方式 传统=1,lombok注解=2 - */ - private static final Integer SET_PO_Getter = 1; - //endregion - - //region po类头部文字设置 - private static final String SET_BEFORE_TEXT = - "/**\n" + - "# __----~~~~~~~~~~~------___\n" + - "# . . ~~//====...... __--~ ~~\n" + - "# -. \\_|// |||\\\\ ~~~~~~::::... /~\n" + - "# ___-==_ _-~o~ \\/ ||| \\\\ _/~~-\n" + - "# __---~~~.==~||\\=_ -_--~/_-~|- |\\\\ \\\\ _/~\n" + - "# _-~~ .=~ | \\\\-_ '-~7 /- / || \\ /\n" + - "# .~ .~ | \\\\ -_ / /- / || \\ /\n" + - "# / ____ / | \\\\ ~-_/ /|- _/ .|| \\ /\n" + - "# |~~ ~~|--~~~~--_ \\ ~==-/ | \\~--===~~ .\\\n" + - "# ' ~-| /| |-~\\~~ __--~~\n" + - "# |-~~-_/ | | ~\\_ _-~ /\\\n" + - "# / \\ \\__ \\/~ \\__\n" + - "# _--~ _/ | .-~~____--~-/ ~~==.\n" + - "# ((->/~ '.|||' -_| ~~-/ , . _||\n" + - "# -_ ~\\ ~~---l__i__i__i--~~_/\n" + - "# _-~-__ ~) \\--______________--~~\n" + - "# //.-~~~-~_--~- |-------~~~~~~~~\n" + - "# //.-~~~--\\\n" + - "# 神兽保佑\n" + - "# 永无BUG!\n" + - "*/"; - //endregion - - //region po类 import 内容设置 - private static final String[] SET_PO_IMPORT = new String[]{ - "import javax.persistence.*;", - "import java.io.Serializable;", - "import java.sql.Timestamp;" - }; - //endregion - - //region vo类 import 内容设置 - private static final String[] SET_VO_IMPORT = new String[]{ - "import com.lunhan.xxx.common.util.LocalDateTimeUtil;", - "import com.lunhan.xxx.common.util.NumericUtil;", - "import java.util.Objects;" - }; - //endregion - - //region 实体映射类 import 内容设置 - private static final String[] SET_CONVERT_IMPORT = new String[]{ - "import org.mapstruct.Mapper;" + - "import org.mapstruct.factory.Mappers;" + - "" + - "import java.util.List;" - }; - //endregion - - //region 字段名枚举类 import 内容设置 - private static final String[] SET_COLUMNS_ENUM_IMPORT = new String[]{ - "import com.lunhan.xxx.common.orm2.enums.ColumnBasic;", - "import java.util.Arrays;", - "import java.util.Objects;" - }; - //endregion - - //region dao类 import 内容设置 - private static final String[] SET_DAO_IMPORT = new String[]{ - "import com.lunhan.xxx.common.ConstantFactory;", - "import com.lunhan.xxx.common.PagerResult;", - "import com.lunhan.xxx.common.orm2.SqlBuilder;", - "import com.lunhan.xxx.common.util.*;", - "import com.lunhan.xxx.entity.dto.OrderByDTO;", - "import com.lunhan.xxx.entity.enums.*;", - "import com.lunhan.xxx.repository.BasicDao;", - "import org.springframework.stereotype.Repository;", - "import java.util.*;", - "import org.springframework.transaction.annotation.Transactional;" - }; - //endregion - - //region service类 import 内容设置 - private static final String[] SET_Service_IMPORT = new String[]{ - "import com.lunhan.xxx.common.*;", - "import com.lunhan.xxx.common.model.Tuple;", - "import com.lunhan.xxx.common.util.*;", - "import org.apache.commons.lang3.BooleanUtils;", - "import org.springframework.beans.factory.annotation.Autowired;", - "import org.springframework.stereotype.Service;", - "import java.util.ArrayList;", - "import java.util.List;", - "import java.util.Objects;" - }; - //endregion - - //region Controller类 import 内容设置 - private static final String[] SET_Controller_IMPORT = new String[]{ - "import com.lunhan.xxx.common.ExecutedResult;", - "import com.lunhan.xxx.common.PagerResult;", - "import com.lunhan.xxx.common.util.ParameterUtil;", - "import com.lunhan.xxx.common.validator.ParameterValidateResult;", - "import com.lunhan.xxx.common.validator.ParameterValidator;", - "import com.lunhan.xxx.entity.request.ReqListId;", - "import com.lunhan.xxx.host.BasicController;", - "import org.springframework.beans.factory.annotation.Autowired;", - "import org.springframework.web.bind.annotation.*;", - "import java.util.List;" - }; - //endregion - - //region search类 import 内容设置 - private static final String[] SET_SEARCH_IMPORT = new String[]{ - "import " + PackageSet.SEARCH.replaceAll("\\.search", "") + ".SearchBasicDTO;", - }; - //endregion - - //region 类注释模版 - private static final String SET_CLASS_DESC_TPL = - "/**\n" + - " * {#=desc}\n" + - " * @author {#=author}\n" + - " * @description {#=desc}\n" + - " */"; - private static final String SET_METHOD_DESC_TPL = - " /**\n" + - " * {#=desc}\n" + - " * @author {#=author}\n" + - " * @description {#=desc}\n" + - " */"; - private static final String SET_PRO_DESC_TPL = - "\t/**\n" + - "\t * {#=desc}\n" + - "\t */"; - //endregion - - //#region 创建接口忽略字段配置 - private static final List<String> NO_CREATE_COLUMNS = Arrays.asList( - "id", - "create_time", "create_user", "create_user_id", "create_user_name", - "update_time", "update_user", "update_user_id", "update_user_name", - "datachange_lasttime", "data_change_last_time", "is_delete", "status", "state" - ); - //#endregion - - //#region 编辑接口忽略字段配置 - private static final List<String> NO_UPDATE_COLUMNS = Arrays.asList( - "create_time", "create_user", "create_user_id", "create_user_name", - "update_time", "update_user", "update_user_id", "update_user_name", - "datachange_lasttime", "data_change_last_time", "is_delete" - ); - private static final List<String> UPDATE_TIME_COLUMNS = Arrays.asList( - "update_time", "datachange_lasttime", "data_change_last_time" - ); - //#endregion - - static { - //加载驱动 - try { - Class.forName(DRIVER); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - //获得连接 - try { - CONN = DriverManager.getConnection(CONNECTION_STR, USER, PASSWORD); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - /** - * 只生成以下配置的表 - */ - private static final List<String> ONLY_TABLES = Arrays.asList( - "water_meter_installation_cost" - ); - - public static void main(String[] args) { - if (null == CONN) { - System.out.println("conn is null."); - return; - } - Map<String, String> tables = getTables(DB_NAME); - for (Map.Entry<String, String> table : tables.entrySet()) { - String tableName = table.getKey(); - String tableDesc = table.getValue(); - System.out.println(tableName + " - " + tableDesc); - if (ONLY_TABLES.size() > 0 && BooleanUtils.isFalse(ONLY_TABLES.contains(tableName))) { - continue; - } - List<Map<String, Object>> columns = getColumns(tableName, DB_NAME); - genPO(columns, tableDesc); - genVO(columns, tableDesc); - genColumnsEnum(columns, tableDesc); - genCreateDto(columns, tableName, tableDesc); - genModifyDto(columns, tableName, tableDesc); - genDao(tableName, tableDesc); - genSearch(columns, tableDesc); - genConvertMapper(tableName, tableDesc); - genService(tableName, tableDesc); - genController(tableName, tableDesc); - - //genMapperXml(columns, tableDesc); - //genMapper(columns, tableDesc); - } - } - - private static void genPO(List<Map<String, Object>> columns, String tableDesc) { - if (ListUtil.isNullOrEmpty(columns)) { - return; - } - String tableName = columns.get(0).get("objname").toString(); - String modelName = underline2Camel(tableName, true); - String poName = modelName + SuffixSet.PO; - boolean isData = Objects.equals(SET_PO_Getter, 2); - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.PO); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (isData) { - content.append(ConstantFactory.STR_NEWLINE); - content.append("import lombok.Data;"); - content.append(ConstantFactory.STR_NEWLINE); - } - if (SET_PO_IMPORT.length > 0) { - content.append(ConstantFactory.STR_NEWLINE); - for (String s : SET_PO_IMPORT) { - content.append(s); - content.append(ConstantFactory.STR_NEWLINE); - } - } - - boolean hasBigDecimal = false; - List<String> listColumn = new ArrayList<>(); - List<String> listGetterSetter = new ArrayList<>(); - for (Map<String, Object> column : columns) { - String name = column.get("name").toString(); - String desc = String.valueOf(column.get("description")); - String type = column.get("type").toString(); - int length = NumericUtil.tryParseInt(column.get("length"), 0); - String defValue = String.valueOf(column.get("default")); - int isPK = NumericUtil.tryParseInt(column.get("isPK"), 0); - int isIdentity = NumericUtil.tryParseInt(column.get("isidentity"), 0); - int isNullable = NumericUtil.tryParseInt(column.get("isnullable"), 0); - - String javaType = getJavaType(type); - if ("BigDecimal".equalsIgnoreCase(javaType)) { - hasBigDecimal = true; - } - String propName = underline2Camel(name); - String columnNameUpper = underline2Camel(name, true); - - listColumn.add(SET_PRO_DESC_TPL.replaceAll("\\{\\#\\=desc\\}", desc)); - if (Objects.equals(isPK, 1)) { - listColumn.add("\t@Id"); - } - if (Objects.equals(isIdentity, 1)) { - listColumn.add("\t@GeneratedValue(strategy = GenerationType.AUTO)"); - } - String columnAnnotation = "\t@Column(name = \"" + name + "\""; - //忽略最后修改时间这一列的新增和编辑 - if (UPDATE_TIME_COLUMNS.stream().anyMatch(c -> c.equalsIgnoreCase(name))) { - columnAnnotation += ", insertable = false, updatable = false"; - } - if ("datachange_lasttime".equalsIgnoreCase(name)) { - propName = "dataChangeLastTime"; - columnNameUpper = "DataChangeLastTime"; - } - listColumn.add(columnAnnotation + ")"); - //追加列 - listColumn.add(String.format("\tprivate %s %s;", javaType, propName)); - - listGetterSetter.add(""); - listGetterSetter.add(String.format("\tpublic %s get%s() {", javaType, columnNameUpper)); - listGetterSetter.add(String.format("\t\treturn this.%s;", propName)); - listGetterSetter.add("\t}"); - listGetterSetter.add(String.format("\tpublic void set%s(%s %s) {", columnNameUpper, javaType, propName)); - listGetterSetter.add(String.format("\t\tthis.%s = %s;", propName, propName)); - listGetterSetter.add("\t}"); - } - if (hasBigDecimal) { - content.append("import java.math.BigDecimal;"); - content.append(ConstantFactory.STR_NEWLINE); - } - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - if (isData) { - content.append("@Data"); - content.append(ConstantFactory.STR_NEWLINE); - } - content.append("@Entity"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("@Table(name = \"" + tableName); - content.append("\")"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("public class "); - content.append(poName); - content.append(" implements Serializable {"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(StringUtil.join(listColumn, ConstantFactory.STR_NEWLINE)); - content.append(ConstantFactory.STR_NEWLINE); - content.append(StringUtil.join(listGetterSetter, ConstantFactory.STR_NEWLINE)); - content.append(ConstantFactory.STR_NEWLINE); - content.append("}"); - - writeFile(OutSet.PO, modelName + SuffixSet.PO + ".java", content.toString()); - } - - private static void genVO(List<Map<String, Object>> columns, String tableDesc) { - if (ListUtil.isNullOrEmpty(columns)) { - return; - } - String tableName = columns.get(0).get("objname").toString(); - String modelName = underline2Camel(tableName, true); - String poName = modelName + SuffixSet.PO; - String voName = modelName + SuffixSet.VO; - boolean isData = Objects.equals(SET_PO_Getter, 2); - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.VO); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (isData) { - content.append(ConstantFactory.STR_NEWLINE); - content.append("import lombok.Data;"); - content.append(ConstantFactory.STR_NEWLINE); - } - if (SET_VO_IMPORT.length > 0) { - content.append(ConstantFactory.STR_NEWLINE); - for (String s : SET_VO_IMPORT) { - content.append(s); - content.append(ConstantFactory.STR_NEWLINE); - } - } - content.append("import "); - content.append(PackageSet.PO); - content.append("."); - content.append(poName + ";\n"); - - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - if (isData) { - content.append("@Data"); - content.append(ConstantFactory.STR_NEWLINE); - } - content.append(ConstantFactory.STR_NEWLINE); - content.append("public class "); - content.append(voName); - content.append(" extends " + poName + " implements BasicVO {\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" @Override\n" + - " public String getCreateTimeView() {\n" + - " if (NumericUtil.tryParseLong(this.getCreateTime()).compareTo(0L) > 0) {\n" + - " return LocalDateTimeUtil.toFormatString(this.getCreateTime());\n" + - " }\n" + - " return \"\";\n" + - " }\n" + - "\n" + - " @Override\n" + - " public String getUpdateTimeView() {\n" + - " if (Objects.isNull(this.getUpdateTime())) {\n" + - " return \"\";\n" + - " }\n" + - " return LocalDateTimeUtil.toFormatFullString(this.getUpdateTime());\n" + - " }"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("}"); - - if (new File(OutSet.VO + modelName + SuffixSet.VO + ".java").exists()) { - return; - } - writeFile(OutSet.VO, modelName + SuffixSet.VO + ".java", content.toString()); - } - - private static void genSearch(List<Map<String, Object>> columns, String tableDesc) { - if (ListUtil.isNullOrEmpty(columns)) { - return; - } - String tableName = columns.get(0).get("objname").toString(); - String modelName = underline2Camel(tableName, true); - String searchName = "Search" + modelName; - String tableNamePackage = tableName.toLowerCase().replaceAll("_", ""); - - StringBuilder content = new StringBuilder(); - content.append("package "); - content.append(PackageSet.SEARCH + ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (SET_SEARCH_IMPORT.length > 0) { - content.append(ConstantFactory.STR_NEWLINE); - for (String s : SET_SEARCH_IMPORT) { - content.append(s); - content.append(ConstantFactory.STR_NEWLINE); - } - } - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append("public class " + searchName + " extends SearchBasicDTO {"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t@Override"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\tpublic String toString() {"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\treturn \"" + searchName + "{\" + \"'\" +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\"keywords='\" + getKeywords() +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\", listId =\" + getListId() +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\", status =\" + getStatus() +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\", listStatus =\" + getListStatus() +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\", createTimeRange='\" + getCreateTimeRange() + \"'\" +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\", createTimeStart =\" + getCreateTimeEnd() +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\", createTimeEnd =\" + getCreateTimeEnd() +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\", lastId =\" + getListId() +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t\t\", orderBy='\" + getOrderBy() + \"'\" +"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t\t'}';"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t}"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("}"); - - if (new File(OutSet.SEARCH + "/" + searchName + ".java").exists()) { - return; - } - writeFile(OutSet.SEARCH + "/", searchName + ".java", content.toString()); - } - - private static void genColumnsEnum(List<Map<String, Object>> columns, String tableDesc) { - if (ListUtil.isNullOrEmpty(columns)) { - return; - } - String tableName = columns.get(0).get("objname").toString(); - String modelName = underline2Camel(tableName, true); - String enumName = "E" + modelName + SuffixSet.COLUMNS_ENUM; - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.COLUMNS_ENUM); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (SET_COLUMNS_ENUM_IMPORT.length > 0) { - content.append(ConstantFactory.STR_NEWLINE); - for (String s : SET_COLUMNS_ENUM_IMPORT) { - content.append(s); - content.append(ConstantFactory.STR_NEWLINE); - } - } - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append("public enum "); - content.append(enumName); - content.append(" implements ColumnBasic {"); - - List<String> listColumn = new ArrayList<>(); - String lastStr = ""; - int idx = 0; - for (Map<String, Object> column : columns) { - idx++; - String name = column.get("name").toString(); - String desc = String.valueOf(column.get("description")); - String type = column.get("type").toString(); - int length = NumericUtil.tryParseInt(column.get("length"), 0); - String defValue = String.valueOf(column.get("default")); - int isPK = NumericUtil.tryParseInt(column.get("isPK"), 0); - int isIdentity = NumericUtil.tryParseInt(column.get("isIdentity"), 0); - int isNullable = NumericUtil.tryParseInt(column.get("isNullable"), 0); - - String propName = underline2Camel(name); - - listColumn.add(SET_PRO_DESC_TPL.replaceAll("\\{\\#\\=desc\\}", desc)); - String str = String.format("\t%s(\"%s\", %s),", name.toUpperCase(), name, idx); - //追加列 - listColumn.add(str); - lastStr = str; - } - content.append(ConstantFactory.STR_NEWLINE); - content.append(StringUtil.join(listColumn, ConstantFactory.STR_NEWLINE).replace(lastStr, lastStr.replace("),", ");"))); - content.append(ConstantFactory.STR_NEWLINE); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\tprivate String columnName;\n"); - content.append("\tprivate Integer value;\n"); - content.append("\tpublic Integer getValue() {\n"); - content.append("\t\treturn value;\n"); - content.append("\t}\n"); - content.append("\tpublic String getColumnName() {\n"); - content.append("\t\treturn columnName;\n"); - content.append("\t}\n"); - content.append("\tstatic final String TABLE_NAME = \"" + tableName + "\";\n"); - content.append("\tpublic String getTableName() {\n"); - content.append("\t\treturn TABLE_NAME;\n"); - content.append("\t}\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t"); - content.append(enumName); - content.append("(String columnName, Integer value) {\n"); - content.append("\t\tthis.columnName = columnName;\n"); - content.append("\t\tthis.value = value;\n"); - content.append("\t}\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\tpublic static " + enumName + " getByValue(Integer value) {\n"); - content.append("\t\treturn Arrays.stream(" + enumName + ".values())\n"); - content.append("\t\t\t\t.filter(e -> Objects.equals(e.getValue(), value))\n"); - content.append("\t\t\t\t.findAny()\n"); - content.append("\t\t\t\t.orElse(null);\n"); - content.append("\t}\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t@Override\n"); - content.append("\tpublic String toString() {\n"); - content.append("\t\treturn \"" + enumName + "{\" +\n"); - content.append("\t\t\t\t\"columnName='\" + columnName + '\\'' +\n"); - content.append("\t\t\t\t\", value=\" + value +\n"); - content.append("\t\t\t\t'}';\n"); - content.append("\t}\n"); - content.append("}"); - - writeFile(OutSet.COLUMNS_ENUM, enumName + ".java", content.toString()); - } - - private static void genDao(String tableName, String tableDesc) { - String modelName = underline2Camel(tableName, true); - String daoName = modelName + SuffixSet.DAO; - String poName = modelName + SuffixSet.PO; - String enumName = "E" + modelName; - String searchName = "Search" + modelName; - String tableNamePackage = tableName.toLowerCase().replaceAll("_", ""); - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.DAO); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (SET_DAO_IMPORT.length > 0) { - content.append(ConstantFactory.STR_NEWLINE); - for (String s : SET_DAO_IMPORT) { - content.append(s); - content.append(ConstantFactory.STR_NEWLINE); - } - } - content.append("import "); - content.append(PackageSet.COLUMNS_ENUM); - content.append("."); - content.append("E" + modelName + SuffixSet.COLUMNS_ENUM + ";\n"); - content.append("import "); - content.append(PackageSet.PO); - content.append("."); - content.append(poName + ";\n"); - content.append("import "); - content.append(PackageSet.SEARCH + "."); - content.append(searchName + ";\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append("@Repository\n"); - content.append("public class "); - content.append(daoName); - content.append(" extends BasicDao<"); - content.append(modelName + SuffixSet.PO); - content.append("> {"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("\t" + daoName + "() {\n"); - content.append("\t\tsuper(E" + modelName + SuffixSet.COLUMNS_ENUM + ".values());\n"); - content.append("\t}\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" /**\n" + - " * 批量删除数据\n" + - " * @param listId 主键id列表\n" + - " * @return 是否成功\n" + - " */\n" + - " public Boolean removeByListId(List<Long> listId) {\n" + - " return super.remove(new SqlBuilder().where(" + enumName + ".ID.in(listId)));\n" + - " }\n\n"); - content.append(" /**\n" + - " * 根据主键获取数据列表\n" + - " * @param listId 主键id列表\n" + - " * @return 数据实体\n" + - " */\n" + - " @Transactional(readOnly = true)\n" + - " public List<" + poName + "> getListById(List<Long> listId) {\n" + - " return super.getList(new SqlBuilder()\n" + - " .where(" + enumName + ".ID.in(listId))\n" + - " );\n" + - " }\n\n"); - content.append("\tpublic PagerResult<" + poName + "> search(" + searchName + " search) {\n" + - "\t\tSqlBuilder builder = new SqlBuilder()\n" + - "\t\t\t\t// 分页参数\n" + - "\t\t\t\t.page(NumericUtil.tryParseInt(search.getPage(), 1), NumericUtil.tryParseInt(search.getLimit(), 1))\n" + - "\n" + - "\t\t\t\t// 数据非逻辑删除\n" + - "\t\t\t\t//.and(" + enumName + ".IS_DELETE.equal(EYesOrNo.NO.getValue()))\n" + - "\t\t\t\t// 状态非删除状态\n" + - "\t\t\t\t//.and(" + enumName + ".STATUS.notEqual(EState.DELETED.getValue()))\n" + - "\n" + - "\t\t\t\t// 状态\n" + - "\t\t\t\t//.andIf(NumericUtil.tryParseInt(search.getStatus()).compareTo(0) > 0, " + enumName + ".STATUS.equal(search.getStatus()))\n" + - "\t\t\t\t// 状态列表\n" + - "\t\t\t\t//.andIf(ListUtil.isNotNullOrEmpty(search.getListStatus()), " + enumName + ".STATUS.in(search.getListStatus()))\n" + - "\t\t\t\t// id列表\n" + - "\t\t\t\t.andIf(ListUtil.isNotNullOrEmpty(search.getListId()), " + enumName + ".ID.in(search.getListId()))\n" + - "\t\t\t\t// 关键字\n" + - "\t\t\t\t//.andIf(StringUtil.isNotNullOrEmpty(search.getKeywords()), " + enumName + ".NAME.like(search.getKeywords()))\n" + - "\t\t\t\t// 创建时间-起始\n" + - "\t\t\t\t.andIf(NumericUtil.tryParseLong(search.getCreateTimeStart()).compareTo(0L) > 0, " + enumName + ".CREATE_TIME.greaterOrEqual(search.getCreateTimeStart()))\n" + - "\t\t\t\t// 创建时间-截止\n" + - "\t\t\t\t.andIf(NumericUtil.tryParseLong(search.getCreateTimeEnd()).compareTo(0L) > 0, " + enumName + ".CREATE_TIME.lessOrEqual(search.getCreateTimeEnd()))\n" + - "\t\t\t\t;\n" + - "\t\tif (ListUtil.isNotNullOrEmpty(search.getOrderBy())) {\n" + - "\t\t\tList<String> listOrderBy = new ArrayList<>();\n" + - "\t\t\tfor (OrderByDTO item : search.getOrderBy()) {\n" + - "\t\t\t\tEOrderBy orderBy = EOrderBy.getByValue(NumericUtil.tryParseInt(item.getOrderBy(), 1));\n" + - "\t\t\t\tif (Objects.isNull(orderBy)) {\n" + - "\t\t\t\t\tcontinue;\n" + - "\t\t\t\t}\n" + - "\t\t\t\tswitch (orderBy) {\n" + - "\t\t\t\t\tcase ID:\n" + - "\t\t\t\t\t\tlistOrderBy.add(" + enumName + ".ID.getColumnName() +\n" + - "\t\t\t\t\t\t\t\t(item.getIsAsc() ? ConstantFactory.SQL_ASC : ConstantFactory.SQL_DESC)\n" + - "\t\t\t\t\t\t);\n" + - "\t\t\t\t\t\tbreak;\n" + - "\n" + - "\t\t\t\t\tcase CREATE_TIME:\n" + - "\t\t\t\t\t\tlistOrderBy.add(" + enumName + ".CREATE_TIME.getColumnName() +\n" + - "\t\t\t\t\t\t\t\t(item.getIsAsc() ? ConstantFactory.SQL_ASC : ConstantFactory.SQL_DESC)\n" + - "\t\t\t\t\t\t);\n" + - "\t\t\t\t\t\tbreak;\n" + - "\n" + - "\t\t\t\t\tcase UPDATE_TIME:\n" + - "\t\t\t\t\t\tlistOrderBy.add(" + enumName + ".UPDATE_TIME.getColumnName() +\n" + - "\t\t\t\t\t\t\t\t(item.getIsAsc() ? ConstantFactory.SQL_ASC : ConstantFactory.SQL_DESC)\n" + - "\t\t\t\t\t\t);\n" + - "\t\t\t\t\t\tbreak;\n" + - "\n" + - "\t\t\t\t\tdefault:\n" + - "\t\t\t\t\t\tbreak;\n" + - "\t\t\t\t}\n" + - "\t\t\t}\n" + - "\t\t\tbuilder.orderBy(ListUtil.toArray(listOrderBy));\n" + - "\t\t}else {\n" + - "\t\t\tbuilder.orderBy(" + enumName + ".ID.getColumnName() + ConstantFactory.SQL_DESC);\n" + - "\t\t}\n"+ - "\t\treturn super.getPageList(builder);\n" + - "\t\t}"); - content.append("}"); - - if (new File(OutSet.DAO + daoName + ".java").exists()) { - return; - } - writeFile(OutSet.DAO, daoName + ".java", content.toString()); - } - - private static Boolean IsNoCreate(String name, Integer isPK, Integer isIdentity) { - if (Objects.equals(isPK, 1) || Objects.equals(isIdentity, 1) || NO_CREATE_COLUMNS.stream().anyMatch(c -> c.equalsIgnoreCase(name))) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - private static Boolean IsNoModify(String name) { - if (NO_UPDATE_COLUMNS.stream().anyMatch(c -> c.equalsIgnoreCase(name))) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - private static void genCreateDto(List<Map<String, Object>> columns, String tabName, String tableDesc) { - if (ListUtil.isNullOrEmpty(columns)) { - return; - } - String tableName = columns.get(0).get("objname").toString(); - String modelName = underline2Camel(tableName, true); - String poName = modelName + SuffixSet.PO; - String createDTOName = SuffixSet.Create + modelName; - boolean isData = Objects.equals(SET_PO_Getter, 2); - String tableNamePackage = tableName.toLowerCase().replaceAll("_", ""); - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.Request + "." + tableNamePackage); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (isData) { - content.append(ConstantFactory.STR_NEWLINE); - content.append("import lombok.Data;"); - content.append(ConstantFactory.STR_NEWLINE); - } - - boolean hasBigDecimal = false; - List<String> listColumn = new ArrayList<>(); - List<String> listGetterSetter = new ArrayList<>(); - for (Map<String, Object> column : columns) { - String name = column.get("name").toString(); - String desc = String.valueOf(column.get("description")); - String type = column.get("type").toString(); - int length = NumericUtil.tryParseInt(column.get("length"), 0); - String defValue = String.valueOf(column.get("default")); - int isPK = NumericUtil.tryParseInt(column.get("isPK"), 0); - int isIdentity = NumericUtil.tryParseInt(column.get("isIdentity"), 0); - int isNullable = NumericUtil.tryParseInt(column.get("isNullable"), 0); - - String javaType = getJavaType(type); - if ("BigDecimal".equalsIgnoreCase(javaType)) { - hasBigDecimal = true; - } - String propName = underline2Camel(name); - String columnNameUpper = underline2Camel(name, true); - - // 主键和自增列不加入新增接口的入参 - if (GenCodeMySQL.IsNoCreate(name, isPK, isIdentity)) { - continue; - } - listColumn.add(SET_PRO_DESC_TPL.replaceAll("\\{\\#\\=desc\\}", desc)); - //追加列 - listColumn.add(String.format("\tprivate %s %s;", javaType, propName)); - - listGetterSetter.add(""); - listGetterSetter.add(String.format("\tpublic %s get%s() {", javaType, columnNameUpper)); - listGetterSetter.add(String.format("\t\treturn this.%s;", propName)); - listGetterSetter.add("\t}"); - listGetterSetter.add(String.format("\tpublic void set%s(%s %s) {", columnNameUpper, javaType, propName)); - listGetterSetter.add(String.format("\t\tthis.%s = %s;", propName, propName)); - listGetterSetter.add("\t}"); - } - if (hasBigDecimal) { - content.append("import java.math.BigDecimal;"); - content.append(ConstantFactory.STR_NEWLINE); - } - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - if (isData) { - content.append("@Data"); - content.append(ConstantFactory.STR_NEWLINE); - } - content.append(ConstantFactory.STR_NEWLINE); - content.append("public class "); - content.append(createDTOName); - content.append(" {"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(StringUtil.join(listColumn, ConstantFactory.STR_NEWLINE)); - content.append(ConstantFactory.STR_NEWLINE); - content.append(StringUtil.join(listGetterSetter, ConstantFactory.STR_NEWLINE)); - content.append(ConstantFactory.STR_NEWLINE); - content.append("}"); - - if (new File(OutSet.RequestDTO + tableNamePackage + "/" + createDTOName + ".java").exists()) { - return; - } - writeFile(OutSet.RequestDTO + tableNamePackage + "/", createDTOName + ".java", content.toString()); - } - - private static void genModifyDto(List<Map<String, Object>> columns, String tabName, String tableDesc) { - if (ListUtil.isNullOrEmpty(columns)) { - return; - } - String tableName = columns.get(0).get("objname").toString(); - String modelName = underline2Camel(tableName, true); - String poName = modelName + SuffixSet.PO; - String modifyDTOName = SuffixSet.Modify + modelName; - boolean isData = Objects.equals(SET_PO_Getter, 2); - String tableNamePackage = tableName.toLowerCase().replaceAll("_", ""); - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.Request + "." + tableNamePackage); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (isData) { - content.append(ConstantFactory.STR_NEWLINE); - content.append("import lombok.Data;"); - content.append(ConstantFactory.STR_NEWLINE); - } - - boolean hasBigDecimal = false; - List<String> listColumn = new ArrayList<>(); - List<String> listGetterSetter = new ArrayList<>(); - for (Map<String, Object> column : columns) { - String name = column.get("name").toString(); - String desc = String.valueOf(column.get("description")); - String type = column.get("type").toString(); - int length = NumericUtil.tryParseInt(column.get("length"), 0); - String defValue = String.valueOf(column.get("default")); - int isPK = NumericUtil.tryParseInt(column.get("isPK"), 0); - int isIdentity = NumericUtil.tryParseInt(column.get("isIdentity"), 0); - int isNullable = NumericUtil.tryParseInt(column.get("isNullable"), 0); - - String javaType = getJavaType(type); - if ("BigDecimal".equalsIgnoreCase(javaType)) { - hasBigDecimal = true; - } - String propName = underline2Camel(name); - String columnNameUpper = underline2Camel(name, true); - - // 主键和自增列不加入新增接口的入参 - if (GenCodeMySQL.IsNoModify(name)) { - continue; - } - listColumn.add(SET_PRO_DESC_TPL.replaceAll("\\{\\#\\=desc\\}", desc)); - //追加列 - listColumn.add(String.format("\tprivate %s %s;", javaType, propName)); - - listGetterSetter.add(""); - listGetterSetter.add(String.format("\tpublic %s get%s() {", javaType, columnNameUpper)); - listGetterSetter.add(String.format("\t\treturn this.%s;", propName)); - listGetterSetter.add("\t}"); - listGetterSetter.add(String.format("\tpublic void set%s(%s %s) {", columnNameUpper, javaType, propName)); - listGetterSetter.add(String.format("\t\tthis.%s = %s;", propName, propName)); - listGetterSetter.add("\t}"); - } - if (hasBigDecimal) { - content.append("import java.math.BigDecimal;"); - content.append(ConstantFactory.STR_NEWLINE); - } - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - if (isData) { - content.append("@Data"); - content.append(ConstantFactory.STR_NEWLINE); - } - content.append(ConstantFactory.STR_NEWLINE); - content.append("public class "); - content.append(modifyDTOName); - content.append(" {"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(StringUtil.join(listColumn, ConstantFactory.STR_NEWLINE)); - content.append(ConstantFactory.STR_NEWLINE); - content.append(StringUtil.join(listGetterSetter, ConstantFactory.STR_NEWLINE)); - content.append(ConstantFactory.STR_NEWLINE); - content.append("}"); - - if (new File(OutSet.RequestDTO + tableNamePackage + "/" + modifyDTOName + ".java").exists()) { - return; - } - writeFile(OutSet.RequestDTO + tableNamePackage + "/", modifyDTOName + ".java", content.toString()); - } - - private static void genConvertMapper(String tableName, String tableDesc) { - String modelName = underline2Camel(tableName, true); - String poName = modelName + SuffixSet.PO; - String voName = modelName + SuffixSet.VO; - String createDTOName = SuffixSet.Create + modelName; - String modifyDTOName = SuffixSet.Modify + modelName; - String convertMapperName = modelName + "Mapper"; - String tableNamePackage = tableName.toLowerCase().replaceAll("_", ""); - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.CONVERT_MAPPER + ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - content.append(ConstantFactory.STR_NEWLINE); - - content.append("import "); - content.append(PackageSet.Request + "." + tableNamePackage + "."); - content.append(createDTOName + ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - - content.append("import "); - content.append(PackageSet.Request + "." + tableNamePackage + "."); - content.append(modifyDTOName + ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - - content.append("import "); - content.append(PackageSet.PO + "."); - content.append(poName + ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - - content.append("import "); - content.append(PackageSet.VO + "."); - content.append(voName + ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - - if (SET_CONVERT_IMPORT.length > 0) { - content.append(ConstantFactory.STR_NEWLINE); - for (String s : SET_CONVERT_IMPORT) { - content.append(s); - content.append(ConstantFactory.STR_NEWLINE); - } - } - - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append("@Mapper"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("public interface "); - content.append(convertMapperName); - content.append(" {"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" " + convertMapperName + " INSTANCE = Mappers.getMapper(" + convertMapperName + ".class);\n" + - "\n" + - " " + poName + " toCreate(" + createDTOName + " request);\n" + - " " + poName + " toModify(" + modifyDTOName + " request);\n" + - "\n" + - " " + voName + " toVo(" + poName + " item);\n" + - " List<" + voName + "> toVo(List<" + poName + "> list);"); - content.append(ConstantFactory.STR_NEWLINE); - content.append("}"); - - if (new File(OutSet.COMVERT_MAPPER + convertMapperName + ".java").exists()) { - return; - } - writeFile(OutSet.COMVERT_MAPPER, convertMapperName + ".java", content.toString()); - } - - private static void genService(String tableName, String tableDesc) { - String modelName = underline2Camel(tableName, true); - String poName = modelName + SuffixSet.PO; - String serviceName = modelName + SuffixSet.SERVICE; - String daoName = modelName + SuffixSet.DAO; - String createDTOName = SuffixSet.Create + modelName; - String modifyDTOName = SuffixSet.Modify + modelName; - String responseDTOName = modelName + "VO"; - String searchName = "Search" + modelName; - String tableNamePackage = tableName.toLowerCase().replaceAll("_", ""); - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.SERVICE); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (SET_Service_IMPORT.length > 0) { - content.append(ConstantFactory.STR_NEWLINE); - for (String s : SET_Service_IMPORT) { - content.append(s); - content.append(ConstantFactory.STR_NEWLINE); - } - } - content.append("import "); - content.append(PackageSet.DAO); - content.append("."); - content.append(daoName + ";\n"); - content.append("import "); - content.append(PackageSet.PO); - content.append("."); - content.append(poName + ";\n"); - content.append("import "); - content.append(PackageSet.Request); - content.append("." + tableNamePackage + "."); - content.append(createDTOName + ";\n"); - content.append("import "); - content.append(PackageSet.Request); - content.append("." + tableNamePackage + "."); - content.append(modifyDTOName + ";\n"); - content.append("import "); - content.append(PackageSet.SEARCH + "."); - content.append(searchName + ";\n"); - content.append("import "); - content.append(PackageSet.VO); - content.append("."); - content.append(responseDTOName + ";\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append("@Service\n"); - content.append("public class "); - content.append(serviceName); - content.append(" extends BaseService {\n"); - content.append(" @Autowired\n" + - " private " + daoName + " dao;\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" public ExecutedResult<Long> create(" + createDTOName + " request) {\n" + - " // 转换po\n" + - " " + poName + " item = CopierUtil.mapTo(request, " + poName + ".class);\n" + - " // 设置主键id\n" + - " //item.setId(SnowFlakeUtil.getId());\n" + - " // 设置状态\n" + - " //item.setStatus(EState.NORMAL.getValue());\n" + - " // 设置记录创建时间\n" + - " item.setCreateTime(LocalDateTimeUtil.nowTimeStamp());\n" + - " // 是否删除(逻辑删除)初始值\n" + - " //item.setIsDelete(EYesOrNo.NO.getValue());\n" + - "\n" + - " Boolean result = this.dao.add(item);\n" + - " if (BooleanUtils.isFalse(result)) {\n" + - " return ExecutedResult.failed(\"创建[" + tableDesc + "]失败。\");\n" + - " }\n" + - " return ExecutedResult.success(item.getId());\n" + - " }\n" + - "\n" + - " public ExecutedResult<String> modify(" + modifyDTOName + " request) {\n" + - " // 验证记录是否存在\n" + - " ExecutedResult<" + poName + "> checkExists = this.check4Id(request.getId());\n" + - " if (checkExists.isFailed()) {\n" + - " return ExecutedResult.failed(checkExists.getMsg());\n" + - " }\n" + - " // 转换po\n" + - " " + poName + " item = CopierUtil.mapTo(request, " + poName + ".class);\n" + - "\n" + - " Boolean result = this.dao.modify(item);\n" + - " if (BooleanUtils.isFalse(result)) {\n" + - " return ExecutedResult.failed(\"编辑[" + tableDesc + "]失败。\");\n" + - " }\n" + - " return ExecutedResult.success();\n" + - " }\n" + - "\n" + - " public ExecutedResult<" + responseDTOName + "> get(Long id) {\n" + - " " + responseDTOName + " result = new " + responseDTOName + "();\n" + - "\n" + - " " + poName + " find = dao.getById(id);\n" + - " if (null != find) {\n" + - " result = CopierUtil.mapTo(find, " + responseDTOName + ".class);\n" + - " }\n" + - " return ExecutedResult.success(result);\n" + - " }\n" + - "\n" + - "// public ExecutedResult<String> stop(Long id) {\n" + - "// // 验证记录是否存在\n" + - "// ExecutedResult<" + poName + "> checkExists = this.check4Id(id);\n" + - "// if (checkExists.isFailed()) {\n" + - "// return ExecutedResult.failed(checkExists.getMsg());\n" + - "// }\n" + - "// " + poName + " item = new " + poName + "();\n" + - "// item.setId(id);\n" + - "// item.setStatus(EState.DISABLED.getValue());\n" + - "//\n" + - "// Boolean result = this.dao.modify(item);\n" + - "// if (BooleanUtils.isFalse(result)) {\n" + - "// return ExecutedResult.failed(\"停用[" + tableDesc + "]失败。\");\n" + - "// }\n" + - "// return ExecutedResult.success();\n" + - "// }\n" + - "//\n" + - "// public ExecutedResult<String> enable(Long id) {\n" + - "// // 验证记录是否存在\n" + - "// ExecutedResult<" + poName + "> checkExists = this.check4Id(id);\n" + - "// if (checkExists.isFailed()) {\n" + - "// return ExecutedResult.failed(checkExists.getMsg());\n" + - "// }\n" + - "// " + poName + " item = new " + poName + "();\n" + - "// item.setId(id);\n" + - "// item.setStatus(EState.NORMAL.getValue());\n" + - "//\n" + - "// Boolean result = this.dao.modify(item);\n" + - "// if (BooleanUtils.isFalse(result)) {\n" + - "// return ExecutedResult.failed(\"启用[" + tableDesc + "]失败。\");\n" + - "// }\n" + - "// return ExecutedResult.success();\n" + - "// }\n" + - "//\n" + - "// public ExecutedResult<String> setSort(ReqSetSort request) {\n" + - "// // 验证记录是否存在\n" + - "// ExecutedResult<" + poName + "> checkExists = this.check4Id(request.getId());\n" + - "// if (checkExists.isFailed()) {\n" + - "// return ExecutedResult.failed(checkExists.getMsg());\n" + - "// }\n" + - "// " + poName + " item = new " + poName + "();\n" + - "// item.setId(request.getId());\n" + - "// item.setSort(request.getSort());\n" + - "//\n" + - "// Boolean result = this.dao.modify(item);\n" + - "// if (BooleanUtils.isFalse(result)) {\n" + - "// return ExecutedResult.failed(\"设置[" + tableDesc + "]排序值失败。\");\n" + - "// }\n" + - "// return ExecutedResult.success();\n" + - "// }\n" + - "//\n" + - "// public ExecutedResult<String> remove(Long id) {\n" + - "// Boolean result = this.dao.remove(id);\n" + - "// if (BooleanUtils.isFalse(result)) {\n" + - "// return ExecutedResult.failed(\"删除[" + tableDesc + "]失败。\");\n" + - "// }\n" + - "// return ExecutedResult.success();\n" + - "// }\n" + - "//\n" + - "// public ExecutedResult<String> removeList(List<Long> ids) {\n" + - "// Boolean result = this.dao.removeByListId(ids);\n" + - "// if (BooleanUtils.isFalse(result)) {\n" + - "// return ExecutedResult.failed(\"删除[" + tableDesc + "]失败。\");\n" + - "// }\n" + - "// return ExecutedResult.success();\n" + - "// }\n" + - "\n" + - " public ExecutedResult<List<" + responseDTOName + ">> getList(List<Long> listId) {\n" + - " List<" + responseDTOName + "> result = new ArrayList<>();\n" + - "\n" + - " List<" + poName + "> list = this.dao.getListById(listId);\n" + - " if (ListUtil.isNotNullOrEmpty(list)) {\n" + - " result = CopierUtil.mapTo(list, " + responseDTOName + ".class);\n" + - " }\n" + - " return ExecutedResult.success(result);\n" + - " }\n" + - "\n" + - " public ExecutedResult<PagerResult<" + responseDTOName + ">> search(" + searchName + " search) {\n" + - " // 处理创建时间范围-查询参数\n" + - " Tuple<String, String> createTimeRange = ParameterUtil.getTimeRange(search.getCreateTimeRange());\n" + - " if (StringUtil.isNotNullOrEmpty(createTimeRange.getItem1())) {\n" + - " search.setCreateTimeStart(LocalDateTimeUtil.getTimeStamp(createTimeRange.getItem1()).getTime());\n" + - " }\n" + - " if (StringUtil.isNotNullOrEmpty(createTimeRange.getItem2())) {\n" + - " search.setCreateTimeEnd(LocalDateTimeUtil.getTimeStamp(createTimeRange.getItem2()).getTime());\n" + - " }\n" + - "\n" + - " PagerResult<" + poName + "> pageList = dao.search(search);\n" + - " List<" + responseDTOName + "> listVo = new ArrayList<>();\n" + - " List<" + poName + "> list = pageList.getList();\n" + - " if (ListUtil.isNotNullOrEmpty(list)) {\n" + - " pageList.setLastId(list.get(list.size() - 1).getId());\n" + - " // 转换vo\n" + - " listVo = CopierUtil.mapTo(list, " + responseDTOName + ".class);\n" + - " }\n" + - " PagerResult<" + responseDTOName + "> result = new PagerResult<>(pageList.getLimit(), pageList.getPage(), pageList.getTotal(), listVo);\n" + - " result.setLastId(pageList.getLastId());\n" + - " return ExecutedResult.success(result);\n" + - " }\n" + - "\n" + - " protected ExecutedResult<" + poName + "> check4Id(Long id) {\n" + - " " + poName + " exists = dao.getById(id);\n" + - " if (Objects.isNull(exists)) {\n" + - " return ExecutedResult.failed(\"[" + tableDesc + "]不存在:\" + id);\n" + - " }\n" + - " return ExecutedResult.success(exists);\n" + - " }\n"); - content.append("}"); - - if (new File(OutSet.SERVICE + serviceName + ".java").exists()) { - return; - } - writeFile(OutSet.SERVICE, serviceName + ".java", content.toString()); - } - - private static void genController(String tableName, String tableDesc) { - String apiName = underline2Camel(tableName, false); - String modelName = underline2Camel(tableName, true); - String poName = modelName + SuffixSet.PO; - String voName = modelName + SuffixSet.VO; - String serviceName = modelName + SuffixSet.SERVICE; - String ControllerName = modelName + SuffixSet.Controller; - String createDTOName = SuffixSet.Create + modelName; - String modifyDTOName = SuffixSet.Modify + modelName; - String responseDTOName = modelName + "VO"; - String searchName = "Search" + modelName; - String tableNamePackage = tableName.toLowerCase().replaceAll("_", ""); - - StringBuilder content = new StringBuilder(); - content.append(SET_BEFORE_TEXT); - content.append(ConstantFactory.STR_NEWLINE); - content.append("package "); - content.append(PackageSet.Controller); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - if (SET_Controller_IMPORT.length > 0) { - content.append(ConstantFactory.STR_NEWLINE); - for (String s : SET_Controller_IMPORT) { - content.append(s); - content.append(ConstantFactory.STR_NEWLINE); - } - } - content.append("import "); - content.append(PackageSet.SERVICE); - content.append("."); - content.append(serviceName + ";\n"); - content.append("import "); - content.append(PackageSet.Request); - content.append("." + tableNamePackage + "."); - content.append(createDTOName + ";\n"); - content.append("import "); - content.append(PackageSet.Request); - content.append("." + tableNamePackage + "."); - content.append(modifyDTOName + ";\n"); - content.append("import "); - content.append(PackageSet.SEARCH + "."); - content.append(searchName + ";\n"); - content.append("import "); - content.append(PackageSet.VO); - content.append("."); - content.append(responseDTOName + ";\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc) - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append("@RestController\n" + - "@RequestMapping(value = \"" + apiName + "\")\n"); - content.append("public class "); - content.append(ControllerName); - content.append(" extends BasicController {\n"); - content.append(" @Autowired\n" + - " private " + serviceName + " service;\n"); - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_METHOD_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", "创建[" + tableDesc + "]") - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" @PostMapping(value = \"create\")\n" + - " public ExecutedResult<Long> create(@RequestBody " + createDTOName + " request) {\n" + - " //#region 参数验证\n" + - " ParameterValidator validator = new ParameterValidator()\n" + - " // 非空\n" + - " //.addNotNullOrEmpty(ParameterUtil.named(\"名称\"), request.getName())\n" + - " // 限制最大长度\n" + - " //.addLengthMax(ParameterUtil.named(\"名称\"), request.getName(), ConstantFactory.LENGTH_MAX50)\n" + - " ;\n" + - " ParameterValidateResult result = validator.validate();\n" + - " if (result.getIsFiled()) {\n" + - " return failed(result.getErrorMsg());\n" + - " }\n" + - " //#endregion\n" + - " return this.service.create(request);\n" + - " }\n" + - "\n"); - content.append(SET_METHOD_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", "编辑[" + tableDesc + "]") - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" @PostMapping(value = \"modify\")\n" + - " public ExecutedResult<String> modify(@RequestBody " + modifyDTOName + " request) {\n" + - " //#region 参数验证\n" + - " ParameterValidator validator = new ParameterValidator()\n" + - " // 必须大于0\n" + - " .addGreater(ParameterUtil.named(\"[" + tableDesc + "]id\"), request.getId(), 0L)\n" + - " // 非空\n" + - " //.addNotNullOrEmpty(ParameterUtil.named(\"名称\"), request.getName())\n" + - " // 限制最大长度\n" + - " //.addLengthMax(ParameterUtil.named(\"名称\"), request.getName(), ConstantFactory.LENGTH_MAX50)\n" + - " ;\n" + - " ParameterValidateResult result = validator.validate();\n" + - " if (result.getIsFiled()) {\n" + - " return failed(result.getErrorMsg());\n" + - " }\n" + - " //#endregion\n" + - " return this.service.modify(request);\n" + - " }\n\n"); - content.append(SET_METHOD_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", "获取[" + tableDesc + "]") - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" @GetMapping(value = \"get\")\n" + - " public ExecutedResult<" + voName + "> get(@RequestParam Long id) {\n" + - " return this.service.get(id);\n" + - " }\n\n"); - content.append(SET_METHOD_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", "根据id批量获取[" + tableDesc + "]") - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" @PostMapping(value = \"getList\")\n" + - " public ExecutedResult<List<" + voName + ">> getList(@RequestBody ReqListId request) {\n" + - " return this.service.getList(request.getListId());\n" + - " }\n\n"); - content.append(SET_METHOD_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", "查询[" + tableDesc + "]") - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append(" @PostMapping(value = \"search\")\n" + - " public ExecutedResult<PagerResult<" + voName + ">> search(@RequestBody " + searchName + " request) {\n" + - " return this.service.search(request);\n" + - " }\n"); - content.append("}"); - - if (new File(OutSet.Controller + ControllerName + ".java").exists()) { - return; - } - writeFile(OutSet.Controller, ControllerName + ".java", content.toString()); - } - - private static String genResultMap(Map<String, String> mapResultMap, Map<String, String> mapResultMapDesc) { - List<String> result = new ArrayList<>(); - for (Map.Entry<String, String> entry : mapResultMap.entrySet()) { - String name = entry.getKey(); - result.add("\t\t<!-- " + mapResultMapDesc.get(entry.getKey()) + " -->"); - result.add("\t\t<result property=\"" + entry.getValue() + "\" column=\"" + name + "\" />"); - } - return StringUtil.join(result, ConstantFactory.STR_NEWLINE); - } - - - //#region gen MyBatis mapper - - private static void genMapperXml(List<Map<String, Object>> columns, String tableDesc) { - if (ListUtil.isNullOrEmpty(columns)) { - return; - } - String tableName = columns.get(0).get("objname").toString(); - String modelName = underline2Camel(tableName, true); - - StringBuilder content = new StringBuilder(); - content.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + - "<!DOCTYPE mapper\n" + - " PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n" + - " \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n"); - content.append("<!-- "); - content.append(tableDesc); - content.append(" mapper -->\n"); - content.append(String.format("<mapper namespace=\"%s.%s%s\">\n", PackageSet.MAPPER, modelName, SuffixSet.MAPPER)); - - Map<String, String> mapResultMap = new HashMap<>(); - Map<String, String> mapResultMapDesc = new HashMap<>(); - for (Map<String, Object> column : columns) { - String name = column.get("name").toString(); - String desc = String.valueOf(column.get("description")); - - String propName = underline2Camel(name); - //忽略最后修改时间这一列的新增和编辑 - if ("datachange_lasttime".equalsIgnoreCase(name)) { - propName = "dataChangeLastTime"; - } - - mapResultMap.put(name, propName); - mapResultMapDesc.put(name, desc); - } - - //追加 resultMap - content.append(String.format("\t<resultMap type=\"%s.%s%s\" id=\"resultMap\">\n", PackageSet.PO, modelName, SuffixSet.PO)); - content.append(genResultMap(mapResultMap, mapResultMapDesc)); - content.append("\n\t</resultMap>\n\n"); - - //追加 add 的方法 - content.append(String.format("\t<insert id=\"add\" parameterType=\"%s.%s%s\" keyProperty=\"id\" useGeneratedKeys=\"true\">\n", PackageSet.PO, modelName, SuffixSet.PO)); - content.append(genInsert(tableName, mapResultMap, mapResultMapDesc)); - content.append("\n\t</insert>\n\n"); - - //追加 addBatch 的方法 - content.append(String.format("\t<insert id=\"addBatch\" parameterType=\"%s.%s%s\" useGeneratedKeys=\"true\" keyProperty=\"id\">\n", PackageSet.PO, modelName, SuffixSet.PO)); - content.append(genInsertBath(tableName, mapResultMap, mapResultMapDesc)); - content.append("\n\t</insert>\n\n"); - - //追加 update 的方法 - content.append(String.format("\t<update id=\"update\" parameterType=\"%s.%s%s\" keyProperty=\"id\">\n", PackageSet.PO, modelName, SuffixSet.PO)); - content.append(genUpdate(tableName, mapResultMap, mapResultMapDesc)); - content.append("\n\t</update>\n\n"); - - //追加 updateBatch 的方法 - content.append("\t<update id=\"updateBatch\" parameterType=\"java.util.List\">\n"); - content.append(genUpdateBatch(tableName, mapResultMap, mapResultMapDesc)); - content.append("\n\t</update>\n\n"); - - //追加 delete 的方法 - content.append("\t<delete id=\"delete\">\n"); - content.append("\t\tDELETE FROM `"); - content.append(tableName); - content.append("` WHERE `id` = #{value}\n"); - content.append("\t</delete>\n\n"); - - //追加 deleteBatch 的方法 - content.append("\t<delete id=\"deleteBatch\" parameterType=\"java.util.List\">\n"); - content.append("\t\tDELETE FROM `"); - content.append(tableName); - content.append("` WHERE `id` IN"); - content.append("\t\t<!-- “collection”固定值为list,“item”为循环变量取的别名 -->\n"); - content.append("\t\t<foreach collection=\"list\" item=\"id\" open=\"(\" separator=\",\" close=\")\">\n"); - content.append("\t\t\t#{id}\n"); - content.append("\t\t</foreach>\n"); - content.append("\t</delete>\n\n"); - - //追加 get 的方法 - content.append("\t<select id=\"get\" resultMap=\"resultMap\">\n"); - content.append(genGet(tableName, mapResultMap, mapResultMapDesc)); - content.append("\n\t</select>\n\n"); - - //追加 getCount 的方法 - content.append(String.format("\t<select id=\"getCount\" resultType=\"Long\" parameterType=\"%s.Search%s\">\n", PackageSet.SEARCH, modelName)); - content.append(genGetCount(tableName)); - content.append("\n\t</select>\n\n"); - - //追加 getList 的方法 - content.append(String.format("\t<select id=\"getList\" resultMap=\"resultMap\" parameterType=\"%s.Search%s\">\n", PackageSet.SEARCH, modelName)); - content.append(genGetList(tableName, mapResultMap, mapResultMapDesc)); - content.append("\n\t</select>\n\n"); - - //追加 getListBySql 的方法 - content.append("\t<select id=\"getListBySql\" parameterType=\"java.util.Map\" resultType=\"HashMap\">\n"); - content.append("\t\t${sql}\n"); - content.append("\t</select>\n"); - - content.append("</mapper>"); - - if (new File(OutSet.MAPPERXML + modelName + SuffixSet.MAPPER + ".xml").exists()) { - return; - } - writeFile(OutSet.MAPPERXML, modelName + SuffixSet.MAPPER + ".xml", content.toString()); - } - - private static void genMapper(List<Map<String, Object>> columns, String tableDesc) { - if (ListUtil.isNullOrEmpty(columns)) { - return; - } - String tableName = columns.get(0).get("objname").toString(); - String modelName = underline2Camel(tableName, true); - - StringBuilder content = new StringBuilder(); - content.append("package "); - content.append(PackageSet.MAPPER); - content.append(ConstantFactory.STR_SEMICOLON); - content.append(ConstantFactory.STR_NEWLINE); - content.append(ConstantFactory.STR_NEWLINE); - content.append(String.format("import %s.%s%s;", PackageSet.PO, modelName, SuffixSet.PO)); - content.append(ConstantFactory.STR_NEWLINE); - content.append(ConstantFactory.STR_NEWLINE); - content.append(SET_CLASS_DESC_TPL - .replaceAll("\\{\\#\\=desc\\}", tableDesc + " mapper") - .replaceAll("\\{\\#\\=author\\}", AUTHOR) - .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) - ); - content.append(ConstantFactory.STR_NEWLINE); - content.append(String.format("public interface %s%s extends BasicMapper<%s%s> {", modelName, SuffixSet.MAPPER, modelName, SuffixSet.PO)); - content.append(ConstantFactory.STR_NEWLINE); - content.append("}"); - - if (new File(OutSet.MAPPER + modelName + SuffixSet.MAPPER + ".java").exists()) { - return; - } - writeFile(OutSet.MAPPER, modelName + SuffixSet.MAPPER + ".java", content.toString()); - } - - private static String genInsert(String tableName, Map<String, String> mapResultMap, Map<String, String> mapResultMapDesc) { - List<String> result = new ArrayList<>(); - result.add("\t\tINSERT INTO `" + tableName + "`("); - - List<String> listColumn = new ArrayList<>(); - List<String> listValue = new ArrayList<>(); - for (Map.Entry<String, String> entry : mapResultMap.entrySet()) { - String name = entry.getKey(); - if (NO_CREATE_COLUMNS.stream().anyMatch(c -> c.equalsIgnoreCase(name))) { - continue; - } - listColumn.add("\t\t<!-- " + mapResultMapDesc.get(entry.getKey()) + " -->\n\t\t`" + name + "`"); - - listValue.add("\t\t#{" + entry.getValue() + "}"); - } - result.add(StringUtil.join(listColumn, ",\r\n")); - result.add("\t\t) VALUES("); - result.add(StringUtil.join(listValue, ",\r\n")); - result.add("\t);"); - return StringUtil.join(result, ConstantFactory.STR_NEWLINE); - } - - private static String genInsertBath(String tableName, Map<String, String> mapResultMap, Map<String, String> mapResultMapDesc) { - List<String> result = new ArrayList<>(); - result.add("\t\tINSERT INTO `" + tableName + "`("); - - List<String> listColumn = new ArrayList<>(); - List<String> listValue = new ArrayList<>(); - for (Map.Entry<String, String> entry : mapResultMap.entrySet()) { - String name = entry.getKey(); - if (NO_CREATE_COLUMNS.stream().anyMatch(c -> c.equalsIgnoreCase(name))) { - continue; - } - listColumn.add("\t\t<!-- " + mapResultMapDesc.get(entry.getKey()) + " -->\n\t\t`" + name + "`"); - - listValue.add("\t\t\t#{item." + entry.getValue() + "}"); - } - result.add(StringUtil.join(listColumn, ",\r\n")); - result.add("\t\t) VALUES("); - result.add("\t\t<!-- “collection”固定值为list,“item”为循环变量取的别名 -->"); - result.add("\t\t<foreach collection=\"list\" item=\"item\" separator=\",\">"); - result.add("\t\t\t("); - result.add(StringUtil.join(listValue, ",\r\n")); - result.add("\t\t\t)"); - result.add("\t\t</foreach>"); - result.add("\t\t);"); - return StringUtil.join(result, ConstantFactory.STR_NEWLINE); - } - - private static String genUpdate(String tableName, Map<String, String> mapResultMap, Map<String, String> mapResultMapDesc) { - List<String> result = new ArrayList<>(); - result.add("\t\tUPDATE `" + tableName + "`"); - result.add("\t\t<trim prefix=\"SET\" suffixOverrides=\",\">"); - for (Map.Entry<String, String> entry : mapResultMap.entrySet()) { - String name = entry.getKey(); - String propName = entry.getValue(); - if (NO_UPDATE_COLUMNS.stream().anyMatch(c -> c.equalsIgnoreCase(name))) { - continue; - } - result.add("\t\t\t<!-- " + mapResultMapDesc.get(entry.getKey()) + " -->"); - result.add("\t\t\t<if test=\"null != " + propName + "\">`" + name + "` = #{" + propName + "},</if>"); - } - result.add("\t\t</trim>"); - result.add("\t\tWHERE `id` = #{id}"); - return StringUtil.join(result, ConstantFactory.STR_NEWLINE); - } - - private static String genUpdateBatch(String tableName, Map<String, String> mapResultMap, Map<String, String> mapResultMapDesc) { - List<String> result = new ArrayList<>(); - result.add("\t\t<!-- “collection”固定值为list,“item”为循环变量取的别名 -->"); - result.add("\t\t<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"\" close=\"\" separator=\";\">"); - result.add("\t\t\tUPDATE `" + tableName + "`"); - result.add("\t\t\t<trim prefix=\"SET\" suffixOverrides=\",\">"); - for (Map.Entry<String, String> entry : mapResultMap.entrySet()) { - String name = entry.getKey(); - String propName = entry.getValue(); - if (NO_UPDATE_COLUMNS.stream().anyMatch(c -> c.equalsIgnoreCase(name))) { - continue; - } - result.add("\t\t\t\t<!-- " + mapResultMapDesc.get(entry.getKey()) + " -->"); - result.add("\t\t\t\t<if test=\"null != item." + propName + "\">`" + name + "` = #{item." + propName + "},</if>"); - } - result.add("\t\t\t</trim>"); - result.add("\t\t\tWHERE `id` = #{id}"); - result.add("\t\t</foreach>"); - return StringUtil.join(result, ConstantFactory.STR_NEWLINE); - } - - private static String genGet(String tableName, Map<String, String> mapResultMap, Map<String, String> mapResultMapDesc) { - List<String> result = new ArrayList<>(); - result.add("\t\t<![CDATA[SELECT"); - - List<String> listColumn = new ArrayList<>(); - for (Map.Entry<String, String> entry : mapResultMap.entrySet()) { - String name = entry.getKey(); - listColumn.add("\t\t\t`" + name + "`"); - } - result.add(StringUtil.join(listColumn, ",\r\n")); - result.add("\t\tFROM `" + tableName + "`]]>"); - result.add("\t\tWHERE `id` = #{id}"); - return StringUtil.join(result, ConstantFactory.STR_NEWLINE); - } - - private static String genGetCount(String tableName) { - List<String> result = new ArrayList<>(); - result.add("\t\t<![CDATA[SELECT COUNT(*) FROM `" + tableName + "`]]>"); - result.add("\t\t<!-- 加上“WHERE”前缀,去掉第一个“AND” -->"); - result.add("\t\t<trim prefix=\"WHERE\" prefixOverrides=\"AND \">"); - - result.add("\t\t\t<!-- 自增id -->"); - result.add("\t\t\t<if test=\"null != id and id > 0\">"); - result.add("\t\t\t\tAND `id` = #{id}"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 自增id列表 -->"); - result.add("\t\t\t<if test=\"null != listId and listId.size() > 0\">"); - result.add("\t\t\t\tAND `id` IN"); - result.add("\t\t\t\t<foreach collection=\"listId\" item=\"item\" open=\"(\" separator=\",\" close=\")\">"); - result.add("\t\t\t\t\t#{item}"); - result.add("\t\t\t\t</foreach>"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 数据状态 -->"); - result.add("\t\t\t<if test=\"null != status and status > 0\">"); - result.add("\t\t\t\tAND `status` = #{status}"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 数据状态列表 -->"); - result.add("\t\t\t<if test=\"null != listStatus and listStatus.size() > 0\">"); - result.add("\t\t\t\tAND `status` IN"); - result.add("\t\t\t\t<foreach collection=\"listStatus\" item=\"item\" open=\"(\" separator=\",\" close=\")\">"); - result.add("\t\t\t\t\t#{item}"); - result.add("\t\t\t\t</foreach>"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 关键字模糊搜索 -->"); - result.add("\t\t\t<!-- <if test=\"null != keywords and '' != keywords.trim()\">"); - result.add("\t\t\t\tAND (`user_name` LIKE #{keywords} OR `nick_name` LIKE #{keywords})"); - result.add("\t\t\t</if> -->"); - - result.add("\t\t\t<!-- 数据创建时间-起始 -->"); - result.add("\t\t\t<if test=\"null != createTimeStart and createTimeStart > 0\">"); - result.add("\t\t\t\tAND `create_time` >= #{createTimeStart}"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 数据创建时间-截止 -->"); - result.add("\t\t\t<if test=\"null != createTimeEnd and createTimeEnd > 0\">"); - result.add("\t\t\t\tAND `create_time` <= #{createTimeEnd}"); - result.add("\t\t\t</if>"); - - result.add("\t\t</trim>"); - return StringUtil.join(result, ConstantFactory.STR_NEWLINE); - } - - private static String genGetList(String tableName, Map<String, String> mapResultMap, Map<String, String> mapResultMapDesc) { - List<String> result = new ArrayList<>(); - result.add("\t\t<![CDATA[SELECT"); - - List<String> listColumn = new ArrayList<>(); - for (Map.Entry<String, String> entry : mapResultMap.entrySet()) { - String name = entry.getKey(); - listColumn.add("\t\t`" + name + "`"); - } - result.add(StringUtil.join(listColumn, ",\r\n")); - result.add("\t\tFROM `" + tableName + "`]]>"); - result.add("\t\t<!-- 加上“WHERE”前缀,去掉第一个“AND” -->"); - result.add("\t\t<trim prefix=\"WHERE\" prefixOverrides=\"AND \">"); - - result.add("\t\t\t<!-- 自增id -->"); - result.add("\t\t\t<if test=\"null != id and id > 0\">"); - result.add("\t\t\t\tAND `id` = #{id}"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 自增id列表 -->"); - result.add("\t\t\t<if test=\"null != listId and listId.size() > 0\">"); - result.add("\t\t\t\tAND `id` IN"); - result.add("\t\t\t\t<foreach collection=\"listId\" item=\"item\" open=\"(\" separator=\",\" close=\")\">"); - result.add("\t\t\t\t\t#{item}"); - result.add("\t\t\t\t</foreach>"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 数据状态 -->"); - result.add("\t\t\t<if test=\"null != status and status > 0\">"); - result.add("\t\t\t\tAND `status` = #{status}"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 数据状态列表 -->"); - result.add("\t\t\t<if test=\"null != listStatus and listStatus.size() > 0\">"); - result.add("\t\t\t\tAND `status` IN"); - result.add("\t\t\t\t<foreach collection=\"listStatus\" item=\"item\" open=\"(\" separator=\",\" close=\")\">"); - result.add("\t\t\t\t\t#{item}"); - result.add("\t\t\t\t</foreach>"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 关键字模糊搜索 -->"); - result.add("\t\t\t<!-- <if test=\"null != keywords and '' != keywords.trim()\">"); - result.add("\t\t\t\tAND (`user_name` LIKE #{keywords} OR `nick_name` LIKE #{keywords})"); - result.add("\t\t\t</if> -->"); - - result.add("\t\t\t<!-- 数据创建时间-起始 -->"); - result.add("\t\t\t<if test=\"null != createTimeStart and createTimeStart > 0\">"); - result.add("\t\t\t\tAND `create_time` >= #{createTimeStart}"); - result.add("\t\t\t</if>"); - - result.add("\t\t\t<!-- 数据创建时间-截止 -->"); - result.add("\t\t\t<if test=\"null != createTimeEnd and createTimeEnd > 0\">"); - result.add("\t\t\t\tAND `create_time` <= #{createTimeEnd}"); - result.add("\t\t\t</if>"); - - result.add("\t\t</trim>"); - result.add("\t\t<choose>"); - result.add("\t\t\t<when test=\"null!=orderBy and orderBy.trim()!=''\">"); - result.add("\t\t\t\tORDER BY ${orderBy}"); - result.add("\t\t\t</when>"); - result.add("\t\t\t<otherwise>"); - result.add("\t\t\t\tORDER BY id DESC"); - result.add("\t\t\t</otherwise>"); - result.add("\t\t</choose>"); - result.add("\t\t<if test=\"null!=pageSize and pageSize>0 and null!=lastRowNo and lastRowNo>=0\">"); - result.add("\t\t\tLIMIT ${lastRowNo}, ${pageSize}"); - result.add("\t\t</if>"); - return StringUtil.join(result, ConstantFactory.STR_NEWLINE); - } - - //#endregion - - - private static Map<String, String> getTables(String dbSchema) { - Map<String, String> result = new LinkedHashMap<>(); - String sql = " SELECT TABLE_NAME ,TABLE_COMMENT " + - " FROM information_schema.`TABLES` " + - " WHERE TABLE_SCHEMA = ? "; - try (PreparedStatement pStmt = CONN.prepareStatement(sql)) { - pStmt.setString(1, dbSchema); - try (ResultSet rs = pStmt.executeQuery()) { - while (rs.next()) { - String tableName = rs.getString("TABLE_NAME"); - String tableComment = rs.getString("TABLE_COMMENT"); - result.put(tableName, tableComment); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - return result; - } - - private static List<Map<String, Object>> getColumns(String tableName, String dbSchema) { - List<Map<String, Object>> result = new ArrayList<>(); - String sql = "SELECT " + - "`TABLE_NAME` AS 'objName', " + - "`COLUMN_NAME` AS 'name', " + - "`DATA_TYPE` AS 'type', " + - "`CHARACTER_MAXIMUM_LENGTH` AS 'length', " + - "`COLUMN_COMMENT` AS 'description', " + - "CASE `EXTRA` WHEN 'auto_increment' THEN CONVERT(1,UNSIGNED) ELSE CONVERT(0,UNSIGNED) END AS 'isIdentity', " + - "CASE `COLUMN_KEY` WHEN 'PRI' THEN CONVERT(1,UNSIGNED) ELSE CONVERT(0,UNSIGNED) END AS 'isPK', " + - "`COLUMN_DEFAULT` AS 'default', " + - "CASE `IS_NULLABLE` WHEN 'YES' THEN CONVERT(1,UNSIGNED) ELSE CONVERT(0,UNSIGNED) END AS 'isNullable' " + - "FROM `information_schema`.`COLUMNS` " + - "WHERE `table_name` = ? AND `table_schema` = ?; "; - try (PreparedStatement pStmt = CONN.prepareStatement(sql)) { - pStmt.setString(1, tableName); - pStmt.setString(2, dbSchema); - try (ResultSet rs = pStmt.executeQuery()) { - //获取键名 - ResultSetMetaData md = rs.getMetaData(); - //获取列的数量 - int columnCount = md.getColumnCount(); - while (rs.next()) { - Map<String, Object> column = new HashMap<>(); - for (int i = 1; i <= columnCount; i++) { - String keyName = md.getColumnLabel(i); - Object value = rs.getObject(i); - column.put(keyName, value); - } - result.add(column); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - return result; - } - - private static String getJavaType(String typeName) { - String result = "String"; - switch (typeName) { - case "int": - case "tinyint": - result = "Integer"; - break; - case "char": - case "varchar": - case "nvarchar": - case "text": - result = "String"; - break; - case "datetime": - case "timestamp": - case "timestamp without time zone": - result = "Timestamp"; - break; - case "bit": - result = "Boolean"; - break; - case "numeric": - case "decimal": - result = "BigDecimal"; - break; - case "bigint": - result = "Long"; - break; - case "date": - result = "Date"; - break; - - default: - break; - } - return result; - } - - private static String underline2Camel(String line, boolean... firstIsUpperCase) { - String str = ""; - if (StringUtil.isNullOrEmpty(line)) { - return str; - } else { - StringBuilder sb = new StringBuilder(); - String[] strArr; - // 不包含下划线,且第二个参数是空的 - if (!line.contains("_") && firstIsUpperCase.length == 0) { - sb.append(line.substring(0, 1).toLowerCase()).append(line.substring(1)); - str = sb.toString(); - } else if (!line.contains("_") && firstIsUpperCase.length != 0) { - if (!firstIsUpperCase[0]) { - sb.append(line.substring(0, 1).toLowerCase()).append(line.substring(1)); - str = sb.toString(); - } else { - sb.append(line.substring(0, 1).toUpperCase()).append(line.substring(1)); - str = sb.toString(); - } - } else if (line.contains("_") && firstIsUpperCase.length == 0) { - strArr = line.split("_"); - for (String s : strArr) { - sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1)); - } - str = sb.toString(); - str = str.substring(0, 1).toLowerCase() + str.substring(1); - } else if (line.contains("_") && firstIsUpperCase.length != 0) { - strArr = line.split("_"); - for (String s : strArr) { - sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1)); - } - if (!firstIsUpperCase[0]) { - str = sb.toString(); - str = str.substring(0, 1).toLowerCase() + str.substring(1); - } else { - str = sb.toString(); - } - } - } - return str; - } - - private static void writeFile(String path, String fileName, String content) { - File directory = new File(path); - //如果路径不存在,新建 - if (!directory.exists() && !directory.isDirectory()) { - directory.mkdirs(); - } - File columnFile = new File(path + fileName); - try { - columnFile.createNewFile(); - try (FileWriter fw = new FileWriter(columnFile.getAbsolutePath()); - PrintWriter pw = new PrintWriter(fw)) { - pw.println(content); - pw.flush(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } -} -- Gitblit v1.9.3