package com.nanjing.water;
|
|
import com.nanjing.water.common.ConstantFactory;
|
import com.nanjing.water.common.util.*;
|
import com.nanjing.water.common.util.*;
|
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.time.LocalDate;
|
import java.time.LocalDateTime;
|
import java.util.Date;
|
import java.util.*;
|
import java.util.stream.Collectors;
|
|
public class GenCodeGauss {
|
private static final String HOST = "113.250.189.120";
|
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 = "nanjing_water_system";
|
private static final String AUTHOR = "lin.liu";
|
|
public 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/nanjing/water/repository/po/";
|
public static final String VO = "./src/main/java/com/nanjing/water/repository/vo/";
|
public static final String CONVERT_MAPPER = "./src/main/java/com/nanjing/water/service/convert/";
|
public static final String MAPPER_IMPL = "./src/main/java/com/nanjing/water/repository/impl/";
|
public static final String MAPPER = "./src/main/java/com/nanjing/water/repository/mapper/";
|
public static final String SERVICE = "./src/main/java/com/nanjing/water/service/";
|
public static final String Controller = "./src/main/java/com/nanjing/water/host/controller/";
|
public static final String SEARCH = "./src/main/java/com/nanjing/water/entity/search/";
|
public static final String Request = "./src/main/java/com/nanjing/water/entity/request/";
|
public static final String Response = "./src/main/java/com/nanjing/water/entity/response/";
|
}
|
//endregion
|
|
//region 架包路径设置
|
class PackageSet {
|
public static final String PO = "com.nanjing.water.repository.po";
|
public static final String VO = "com.nanjing.water.repository.vo";
|
public static final String CONVERT_MAPPER = "com.nanjing.water.service.convert";
|
public static final String MAPPER_IMPL = "com.nanjing.water.repository.impl";
|
public static final String MAPPER = "com.nanjing.water.repository.mapper";
|
public static final String SERVICE = "com.nanjing.water.service";
|
public static final String Controller = "com.nanjing.water.host.controller";
|
public static final String SEARCH = "com.nanjing.water.entity.search";
|
public static final String Request = "com.nanjing.water.entity.request";
|
public static final String Response = "com.nanjing.water.entity.response";
|
}
|
//endregion
|
|
//region 后缀名设置
|
class SuffixSet {
|
public static final String PO = "PO";
|
public static final String VO = "VO";
|
public static final String CONVERT_MAPPER = "Convert";
|
public static final String MAPPER_IMPL = "MapperImpl";
|
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 = 2;
|
//endregion
|
|
//region 类头部文字设置
|
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 import依赖架包
|
|
//region po类 import 内容设置
|
private static final String[] SET_PO_IMPORT = new String[]{
|
"import com.baomidou.mybatisplus.annotation.*;",
|
"",
|
"import java.io.Serializable;",
|
"import java.sql.Timestamp;"
|
};
|
//endregion
|
|
//region vo类 import 内容设置
|
private static final String[] SET_VO_IMPORT = new String[]{
|
"import com.nanjing.water.common.util.LocalDateTimeUtil;",
|
"import com.nanjing.water.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 mapper实现类 import 内容设置
|
private static final String[] SET_MAPPER_IMPL_IMPORT = new String[]{
|
"import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;",
|
"import com.baomidou.mybatisplus.extension.plugins.pagination.Page;",
|
"import com.nanjing.water.common.PagerResult;",
|
"import com.nanjing.water.common.enums.EYesOrNo;",
|
"import com.nanjing.water.common.util.*;",
|
"import com.nanjing.water.entity.dto.*;",
|
"import com.nanjing.water.entity.enums.*;",
|
"import com.nanjing.water.repository.BasicMapperImpl;",
|
"import org.springframework.stereotype.Repository;",
|
"",
|
"import java.util.List;"
|
};
|
//endregion
|
|
//region service类 import 内容设置
|
private static final String[] SET_Service_IMPORT = new String[]{
|
"import com.nanjing.water.common.*;",
|
"import com.nanjing.water.common.enums.*;",
|
"import com.nanjing.water.common.model.Tuple;",
|
"import com.nanjing.water.common.util.*;",
|
"import org.apache.commons.lang3.BooleanUtils;",
|
"import org.springframework.beans.factory.annotation.Autowired;",
|
"import org.springframework.stereotype.Service;",
|
"import java.util.*;",
|
"import java.util.stream.Collectors;"
|
};
|
//endregion
|
|
//region Controller类 import 内容设置
|
private static final String[] SET_Controller_IMPORT = new String[]{
|
"import com.nanjing.water.common.ExecutedResult;",
|
"import com.nanjing.water.common.PagerResult;",
|
"import com.nanjing.water.common.util.ParameterUtil;",
|
"import com.nanjing.water.common.validator.ParameterValidateResult;",
|
"import com.nanjing.water.common.validator.ParameterValidator;",
|
"import com.nanjing.water.entity.request.ReqListId;",
|
"import com.nanjing.water.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 " + GenCodeGauss.PackageSet.SEARCH.replaceAll("\\.search", "") + ".dto.SearchBasicDTO;",
|
};
|
//endregion
|
|
//endregion
|
|
//region 类注释模版
|
private static final String SET_CLASS_DESC_TPL =
|
"/**\n" +
|
" * {#=desc}\n" +
|
" * @author {#=author}\n" +
|
" */";
|
private static final String SET_METHOD_DESC_TPL =
|
" /**\n" +
|
" * {#=desc}\n" +
|
" * @author {#=author}\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(
|
"monitor_video_streaming"
|
);
|
|
public static void main(String[] args) {
|
if (null == CONN) {
|
System.out.println("conn is null.");
|
return;
|
}
|
Map<String, String> tables = getTables(CONN, 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(CONN, tableName);
|
genPO(columns, tableDesc);
|
genVO(columns, tableDesc);
|
genCreateDto(columns, tableName, tableDesc);
|
|
genSearch(columns, tableDesc);
|
genMapper(columns, tableDesc);
|
genModifyDto(columns, tableName, tableDesc);
|
genMapperImpl(tableName, tableDesc);
|
genConvertMapper(tableName, tableDesc);
|
genService(tableName, tableDesc);
|
genController(tableName, 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 + GenCodeGauss.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(GenCodeGauss.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@TableId");
|
if (Objects.equals(isIdentity, 1)) {
|
listColumn.add("(type = IdType.AUTO)");
|
} else {
|
listColumn.add("(type = IdType.ASSIGN_ID)");
|
}
|
}
|
if ("is_delete".equals(name)) {
|
String columnAnnotation = "\t@TableLogic";
|
listColumn.add(columnAnnotation);
|
}
|
if (!"id".equals(name)) {
|
String columnAnnotation = "\t@TableField(value = \"" + name + "\"";
|
//忽略最后修改时间这一列的新增和编辑
|
// if (UPDATE_TIME_COLUMNS.stream().anyMatch(c -> c.equalsIgnoreCase(name))) {
|
// columnAnnotation += ", insertable = false, updatable = false";
|
// }
|
listColumn.add(columnAnnotation + ")");
|
}
|
if ("datachange_lasttime".equalsIgnoreCase(name)) {
|
propName = "dataChangeLastTime";
|
columnNameUpper = "DataChangeLastTime";
|
}
|
//追加列
|
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 == null ? modelName : 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("@TableName(\"" + 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);
|
if (!isData) {
|
content.append(StringUtil.join(listGetterSetter, ConstantFactory.STR_NEWLINE));
|
content.append(ConstantFactory.STR_NEWLINE);
|
}
|
content.append("}");
|
|
writeFile(GenCodeGauss.OutSet.PO, modelName + GenCodeGauss.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 + GenCodeGauss.SuffixSet.PO;
|
String voName = modelName + GenCodeGauss.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(GenCodeGauss.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(GenCodeGauss.PackageSet.PO);
|
content.append(".");
|
content.append(poName + ";\n");
|
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(SET_CLASS_DESC_TPL
|
.replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : 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("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(GenCodeGauss.OutSet.VO + modelName + GenCodeGauss.SuffixSet.VO + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.OutSet.VO, modelName + GenCodeGauss.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("_", "");
|
boolean isData = Objects.equals(SET_PO_Getter, 2);
|
|
StringBuilder content = new StringBuilder();
|
content.append("package ");
|
content.append(GenCodeGauss.PackageSet.SEARCH + 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_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 == null ? modelName : tableDesc)
|
.replaceAll("\\{\\#\\=author\\}", AUTHOR)
|
.replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/"))
|
);
|
if (isData) {
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append("@Data");
|
}
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append("public class " + searchName + " extends SearchBasicDTO {");
|
content.append(ConstantFactory.STR_NEWLINE);
|
if (!isData) {
|
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(GenCodeGauss.OutSet.SEARCH + "/" + searchName + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.OutSet.SEARCH + "/", searchName + ".java", content.toString());
|
}
|
|
private static void genMapperImpl(String tableName, String tableDesc) {
|
String modelName = underline2Camel(tableName, true);
|
String mapperName = modelName + SuffixSet.MAPPER;
|
String daoName = modelName + GenCodeGauss.SuffixSet.MAPPER_IMPL;
|
String poName = modelName + GenCodeGauss.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(GenCodeGauss.PackageSet.MAPPER_IMPL);
|
content.append(ConstantFactory.STR_SEMICOLON);
|
content.append(ConstantFactory.STR_NEWLINE);
|
if (SET_MAPPER_IMPL_IMPORT.length > 0) {
|
content.append(ConstantFactory.STR_NEWLINE);
|
for (String s : SET_MAPPER_IMPL_IMPORT) {
|
content.append(s);
|
content.append(ConstantFactory.STR_NEWLINE);
|
}
|
}
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.SEARCH + ".");
|
content.append(searchName + ";\n");
|
content.append("import ");
|
content.append(PackageSet.MAPPER);
|
content.append(".");
|
content.append(mapperName + ";\n");
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.PO);
|
content.append(".");
|
content.append(poName + ";\n");
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(SET_CLASS_DESC_TPL
|
.replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : 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 BasicMapperImpl<");
|
content.append(modelName + GenCodeGauss.SuffixSet.PO);
|
content.append(", " + mapperName + "> {");
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append("\t" + daoName + "(" + mapperName + " mapper) {\n");
|
content.append("\t\tsuper(mapper);\n");
|
content.append("\t}\n");
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append("\t@Override\n" +
|
"\tpublic PagerResult<" + poName + "> search(SearchBasicDTO request) {\n" +
|
"\t\t// 还原查询条件真实类型\n" +
|
"\t\t" + searchName + " search = (" + searchName + ")request;\n" +
|
"\t\t// 查询条件\n" +
|
"\t\tLambdaQueryWrapper<" + poName + "> queryWrapper = this.query();\n" +
|
"\t\t// 非逻辑删除\n" +
|
"\t\tqueryWrapper.eq(" + poName + "::getIsDelete, EYesOrNo.NO.getValue());\n" +
|
"\t\t// 状态\n" +
|
"\t\t//queryWrapper.eq(NumericUtil.tryParseInt(search.getStatus()).compareTo(0) > 0, " + poName + "::getStatus, search.getStatus());\n" +
|
"\t\t// 状态列表\n" +
|
"\t\t//queryWrapper.in(ListUtil.isNotNullOrEmpty(search.getListStatus()), " + poName + "::getStatus, search.getListStatus());\n" +
|
"\n" +
|
"\t\t// 数据创建时间-起始\n" +
|
"\t\tqueryWrapper.ge(NumericUtil.tryParseLong(search.getCreateTimeStart()).compareTo(0L) > 0, " + poName + "::getCreateTime, search.getCreateTimeStart());\n" +
|
"\t\t// 数据创建时间-截止\n" +
|
"\t\tqueryWrapper.le(NumericUtil.tryParseLong(search.getCreateTimeEnd()).compareTo(0L) > 0, " + poName + "::getCreateTime, search.getCreateTimeEnd());\n" +
|
"\t\t// 关键字\n" +
|
"\t\t//if (StringUtil.isNotNullOrEmpty(search.getKeywords())) {\n" +
|
"\t\t//\tqueryWrapper.and(q ->\n" +
|
"\t\t//\t\tq.like(" + poName + "::getName, search.getKeywords())\n" +
|
"\t\t//\t\t.or().like(" + poName + "::getPhone, search.getKeywords())\n" +
|
"\t\t//\t);\n" +
|
"\t\t//}\n" +
|
"\n" +
|
"\t\t// 排序处理\n" +
|
"\t\tif (ListUtil.isNotNullOrEmpty(search.getOrderBy())) {\n" +
|
"\t\t\tfor (OrderByDTO item : search.getOrderBy()) {\n" +
|
"\t\t\t\tEOrderBy orderBy = EOrderBy.getByValue(item.getOrderBy());\n" +
|
"\t\t\t\t// 顺序排序\n" +
|
"\t\t\t\tif (item.getIsAsc()) {\n" +
|
"\t\t\t\t\tswitch (orderBy) {\n" +
|
"\t\t\t\t\t\t// 主键\n" +
|
"\t\t\t\t\t\tcase ID:\n" +
|
"\t\t\t\t\t\t\tqueryWrapper.orderByAsc(" + poName + "::getId);\n" +
|
"\t\t\t\t\t\t\tbreak;\n" +
|
"\t\t\t\t\t\t// 数据创建时间\n" +
|
"\t\t\t\t\t\tcase CREATE_TIME:\n" +
|
"\t\t\t\t\t\t\tqueryWrapper.orderByAsc(" + poName + "::getCreateTime);\n" +
|
"\t\t\t\t\t\t\tbreak;\n" +
|
"\t\t\t\t\t\t// 最后更新时间\n" +
|
"\t\t\t\t\t\tcase UPDATE_TIME:\n" +
|
"\t\t\t\t\t\t\tqueryWrapper.orderByAsc(" + poName + "::getUpdateTime);\n" +
|
"\t\t\t\t\t\t\tbreak;\n" +
|
"\t\t\t\t\t}\n" +
|
"\t\t\t\t} else {\n" +
|
"\t\t\t\t\t// 倒叙排序\n" +
|
"\t\t\t\t\tswitch (orderBy) {\n" +
|
"\t\t\t\t\t\t// 主键\n" +
|
"\t\t\t\t\t\tcase ID:\n" +
|
"\t\t\t\t\t\t\tqueryWrapper.orderByDesc(" + poName + "::getId);\n" +
|
"\t\t\t\t\t\t\tbreak;\n" +
|
"\t\t\t\t\t\t// 数据创建时间\n" +
|
"\t\t\t\t\t\tcase CREATE_TIME:\n" +
|
"\t\t\t\t\t\t\tqueryWrapper.orderByDesc(" + poName + "::getCreateTime);\n" +
|
"\t\t\t\t\t\t\tbreak;\n" +
|
"\t\t\t\t\t\t// 最后更新时间\n" +
|
"\t\t\t\t\t\tcase UPDATE_TIME:\n" +
|
"\t\t\t\t\t\t\tqueryWrapper.orderByDesc(" + poName + "::getUpdateTime);\n" +
|
"\t\t\t\t\t\t\tbreak;\n" +
|
"\t\t\t\t\t}\n" +
|
"\t\t\t\t}\n" +
|
"\t\t\t}\n" +
|
"\t\t} else {\n" +
|
"\t\t\tqueryWrapper.orderByDesc(" + poName + "::getId);\n" +
|
"\t\t}\n" +
|
"\t\tPage<" + poName + "> pageResult = super.selectPage(new Page<>(search.getPage(), search.getLimit()), queryWrapper);\n" +
|
"\t\treturn new PagerResult<>(pageResult.getSize(), pageResult.getCurrent(), pageResult.getTotal(), pageResult.getRecords());\n" +
|
"\t}\n" +
|
"\n" +
|
"\tpublic Boolean add(" + poName + " item) {\n" +
|
"\t\tint rowCount = super.insert(item);\n" +
|
"\t\treturn rowCount == 1;\n" +
|
"\t}\n" +
|
"\n" +
|
"\tpublic Boolean addNotIncrement(" + poName + " item) {\n" +
|
"\t\tint rowCount = super.insert(item);\n" +
|
"\t\treturn rowCount == 1;\n" +
|
"\t}\n" +
|
"\n" +
|
"\tpublic " + poName + " getById(Long id) {\n" +
|
"\t\treturn super.get(id);\n" +
|
"\t}\n" +
|
"\n" +
|
"\tpublic List<" + poName + "> getListById(List<Long> listId) {\n" +
|
"\t\treturn super.getList(listId);\n" +
|
"\t}\n"
|
);
|
content.append("}");
|
|
if (new File(GenCodeGauss.OutSet.MAPPER_IMPL + daoName + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.OutSet.MAPPER_IMPL, 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 + GenCodeGauss.SuffixSet.PO;
|
String createDTOName = GenCodeGauss.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(GenCodeGauss.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 (GenCodeGauss.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 == null ? modelName : 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("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);
|
if (!isData) {
|
content.append(StringUtil.join(listGetterSetter, ConstantFactory.STR_NEWLINE));
|
content.append(ConstantFactory.STR_NEWLINE);
|
}
|
content.append("}");
|
|
if (new File(GenCodeGauss.OutSet.Request + tableNamePackage + "/" + createDTOName + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.OutSet.Request + 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 + GenCodeGauss.SuffixSet.PO;
|
String modifyDTOName = GenCodeGauss.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(GenCodeGauss.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 (GenCodeGauss.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 == null ? modelName : 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("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);
|
if (!isData) {
|
content.append(StringUtil.join(listGetterSetter, ConstantFactory.STR_NEWLINE));
|
content.append(ConstantFactory.STR_NEWLINE);
|
}
|
content.append("}");
|
|
if (new File(GenCodeGauss.OutSet.Request + tableNamePackage + "/" + modifyDTOName + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.OutSet.Request + tableNamePackage + "/", modifyDTOName + ".java", content.toString());
|
}
|
|
private static void genConvertMapper(String tableName, String tableDesc) {
|
String modelName = underline2Camel(tableName, true);
|
String poName = modelName + GenCodeGauss.SuffixSet.PO;
|
String voName = modelName + GenCodeGauss.SuffixSet.VO;
|
String createDTOName = GenCodeGauss.SuffixSet.Create + modelName;
|
String modifyDTOName = GenCodeGauss.SuffixSet.Modify + modelName;
|
String convertMapperName = modelName + SuffixSet.CONVERT_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(GenCodeGauss.PackageSet.CONVERT_MAPPER + ConstantFactory.STR_SEMICOLON);
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(ConstantFactory.STR_NEWLINE);
|
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.Request + "." + tableNamePackage + ".");
|
content.append(createDTOName + ConstantFactory.STR_SEMICOLON);
|
content.append(ConstantFactory.STR_NEWLINE);
|
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.Request + "." + tableNamePackage + ".");
|
content.append(modifyDTOName + ConstantFactory.STR_SEMICOLON);
|
content.append(ConstantFactory.STR_NEWLINE);
|
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.PO + ".");
|
content.append(poName + ConstantFactory.STR_SEMICOLON);
|
content.append(ConstantFactory.STR_NEWLINE);
|
|
content.append("import ");
|
content.append(GenCodeGauss.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 == null ? modelName : 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(GenCodeGauss.OutSet.CONVERT_MAPPER + convertMapperName + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.OutSet.CONVERT_MAPPER, convertMapperName + ".java", content.toString());
|
}
|
|
private static void genService(String tableName, String tableDesc) {
|
String modelName = underline2Camel(tableName, true);
|
String poName = modelName + GenCodeGauss.SuffixSet.PO;
|
String serviceName = modelName + GenCodeGauss.SuffixSet.SERVICE;
|
String daoName = modelName + GenCodeGauss.SuffixSet.MAPPER_IMPL;
|
String createDTOName = GenCodeGauss.SuffixSet.Create + modelName;
|
String modifyDTOName = GenCodeGauss.SuffixSet.Modify + modelName;
|
String responseDTOName = modelName + "VO";
|
String searchName = "Search" + modelName;
|
String convertMapperName = modelName + SuffixSet.CONVERT_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(GenCodeGauss.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(String.format("import %s.%s;\n", GenCodeGauss.PackageSet.MAPPER_IMPL, daoName));
|
content.append(String.format("import %s.%s;\n", GenCodeGauss.PackageSet.PO, poName));
|
content.append(String.format("import %s.%s.%s;\n", GenCodeGauss.PackageSet.Request, tableNamePackage, createDTOName));
|
content.append(String.format("import %s.%s.%s;\n", GenCodeGauss.PackageSet.Request, tableNamePackage, modifyDTOName));
|
content.append(String.format("import %s.%s;\n", GenCodeGauss.PackageSet.SEARCH, searchName));
|
content.append(String.format("import %s.%s;\n", GenCodeGauss.PackageSet.VO, responseDTOName));
|
content.append(String.format("import %s.%s;\n", GenCodeGauss.PackageSet.CONVERT_MAPPER, convertMapperName));
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(SET_CLASS_DESC_TPL
|
.replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : 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 + " mapper;\n");
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(" public ExecutedResult<Long> create(" + createDTOName + " request) {\n" +
|
" // 转换po\n" +
|
" " + poName + " item = " + convertMapperName + ".INSTANCE.toCreate(request);\n" +
|
" // 设置状态\n" +
|
" //item.setStatus(EState.NORMAL.getValue());\n" +
|
" // 设置记录创建时间\n" +
|
" item.setCreateTime(LocalDateTimeUtil.nowTimeStamp());\n" +
|
" // 是否删除(逻辑删除)初始值\n" +
|
" item.setIsDelete(EYesOrNo.NO.getValue());\n" +
|
"\n" +
|
" int rowCount = mapper.insert(item);\n" +
|
" if (rowCount != 1) {\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 = " + convertMapperName + ".INSTANCE.toModify(request);\n" +
|
"\n" +
|
" int rowCount = mapper.updateById(item);\n" +
|
" if (rowCount != 1) {\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 = mapper.get(id);\n" +
|
" if (null != find) {\n" +
|
" // 转换vo\n" +
|
" result = " + convertMapperName + ".INSTANCE.toVo(find);\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" +
|
"// int rowCount = mapper.updateById(item);\n" +
|
"// if (rowCount != 1) {\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" +
|
"// int rowCount = mapper.updateById(item);\n" +
|
"// if (rowCount != 1) {\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" +
|
"// int rowCount = mapper.updateById(item);\n" +
|
"// if (rowCount != 1) {\n" +
|
"// return ExecutedResult.failed(\"设置[" + tableDesc + "]排序值失败。\");\n" +
|
"// }\n" +
|
"// return ExecutedResult.success();\n" +
|
"// }\n" +
|
"//\n" +
|
"// public ExecutedResult<String> listSetSort(ReqListSetSort request) {\n" +
|
"// // id列表\n" +
|
"// List<Long> listId = request.getList().stream().map(ReqSetSort::getId).collect(Collectors.toList());\n" +
|
"// // 验证记录是否存在\n" +
|
"// ExecutedResult<List<" + poName + ">> checkExists = this.check4Id(listId);\n" +
|
"// if (checkExists.isFailed()) {\n" +
|
"// return ExecutedResult.failed(checkExists.getMsg());\n" +
|
"// }\n" +
|
"//\n" +
|
"// List<" + poName + "> listUpdate = request.getList().stream()\n" +
|
"// .map(c -> {\n" +
|
"// " + poName + " item = new " + poName + "();\n" +
|
"// item.setId(c.getId());\n" +
|
"// item.setSort(c.getSort());\n" +
|
"// return item;\n" +
|
"// })\n" +
|
"// .collect(Collectors.toList());\n" +
|
"// Boolean result = mapper.modifyList(listUpdate);\n" +
|
"// if (result) {\n" +
|
"// return ExecutedResult.success();\n" +
|
"// }\n" +
|
"// return ExecutedResult.failed(\"[" + tableDesc + "]设置排序值失败\");\n" +
|
"// }\n" +
|
"//\n" +
|
"// public ExecutedResult<String> remove(Long id) {\n" +
|
"// Boolean result = mapper.deleteLogic(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 = mapper.deleteLogic(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 = mapper.getList(listId);\n" +
|
" if (ListUtil.isNotNullOrEmpty(list)) {\n" +
|
" // 转换vo\n" +
|
" result = " + convertMapperName + ".INSTANCE.toVo(list);\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 = mapper.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 = " + convertMapperName + ".INSTANCE.toVo(list);\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 = mapper.get(id);\n" +
|
" if (Objects.isNull(exists)) {\n" +
|
" return ExecutedResult.failed(\"[" + tableDesc + "]不存在:\" + id);\n" +
|
" }\n" +
|
" return ExecutedResult.success(exists);\n" +
|
" }\n" +
|
" protected ExecutedResult<List<" + poName + ">> check4Id(List<Long> listId) {\n" +
|
" // 从数据库查找" + tableDesc + "\n" +
|
" List<" + poName + "> list = mapper.getList(listId);\n" +
|
" if (ListUtil.isNullOrEmpty(list)) {\n" +
|
" return ExecutedResult.failed(\"[" + tableDesc + "]不存在.\" + listId);\n" +
|
" }\n" +
|
" // 数据库找到的id列表\n" +
|
" List<Long> listIdFind = list.stream().map(" + poName + "::getId).collect(Collectors.toList());\n" +
|
" // 数量不一致\n" +
|
" if (listId.size() != listIdFind.size()) {\n" +
|
" // 筛选数据库不存在的" + tableDesc + "\n" +
|
" List<Long> listIdNotFound = listId.stream().filter(c -> !listIdFind.contains(c)).collect(Collectors.toList());\n" +
|
" if (ListUtil.isNullOrEmpty(list)) {\n" +
|
" return ExecutedResult.failed(\"[" + tableDesc + "]不存在.\" + listIdNotFound);\n" +
|
" }\n" +
|
" }\n" +
|
" return ExecutedResult.success(list);\n" +
|
" }");
|
content.append("}");
|
|
if (new File(GenCodeGauss.OutSet.SERVICE + serviceName + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.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 + GenCodeGauss.SuffixSet.PO;
|
String voName = modelName + GenCodeGauss.SuffixSet.VO;
|
String serviceName = modelName + GenCodeGauss.SuffixSet.SERVICE;
|
String ControllerName = modelName + GenCodeGauss.SuffixSet.Controller;
|
String createDTOName = GenCodeGauss.SuffixSet.Create + modelName;
|
String modifyDTOName = GenCodeGauss.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(GenCodeGauss.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(GenCodeGauss.PackageSet.SERVICE);
|
content.append(".");
|
content.append(serviceName + ";\n");
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.Request);
|
content.append("." + tableNamePackage + ".");
|
content.append(createDTOName + ";\n");
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.Request);
|
content.append("." + tableNamePackage + ".");
|
content.append(modifyDTOName + ";\n");
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.SEARCH + ".");
|
content.append(searchName + ";\n");
|
content.append("import ");
|
content.append(GenCodeGauss.PackageSet.VO);
|
content.append(".");
|
content.append(responseDTOName + ";\n");
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(SET_CLASS_DESC_TPL
|
.replaceAll("\\{\\#\\=desc\\}", "9000." + (tableDesc == null ? modelName : tableDesc))
|
.replaceAll("\\{\\#\\=author\\}", AUTHOR + "\n * @order 9000")
|
.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 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 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/{id}\")\n" +
|
" public ExecutedResult<" + voName + "> get(@PathVariable Long id) {\n" +
|
" return service.get(id);\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 service.search(request);\n" +
|
" }\n");
|
content.append("}");
|
|
if (new File(GenCodeGauss.OutSet.Controller + ControllerName + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.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 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(GenCodeGauss.PackageSet.MAPPER);
|
content.append(ConstantFactory.STR_SEMICOLON);
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(String.format("import %s.BasicMapper;", PackageSet.MAPPER.replace(".mapper", "")));
|
content.append(String.format("import %s.%s%s;", GenCodeGauss.PackageSet.PO, modelName, GenCodeGauss.SuffixSet.PO));
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append(SET_CLASS_DESC_TPL
|
.replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : 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, GenCodeGauss.SuffixSet.MAPPER, modelName, GenCodeGauss.SuffixSet.PO));
|
content.append(ConstantFactory.STR_NEWLINE);
|
content.append("}");
|
|
if (new File(GenCodeGauss.OutSet.MAPPER + modelName + GenCodeGauss.SuffixSet.MAPPER + ".java").exists()) {
|
return;
|
}
|
writeFile(GenCodeGauss.OutSet.MAPPER, modelName + GenCodeGauss.SuffixSet.MAPPER + ".java", content.toString());
|
}
|
|
//#endregion
|
|
|
public static Map<String, String> getTables(Connection connect, String dbSchema) {
|
// dbSchema="public";
|
Map<String, String> result = new LinkedHashMap<>();
|
String sql = "SELECT tb.table_name, d.description AS TABLE_COMMENT" +
|
" FROM information_schema.tables tb" +
|
" JOIN pg_class c ON c.relname = tb.table_name" +
|
" LEFT JOIN pg_description d ON d.objoid = c.oid AND d.objsubid = '0'" +
|
" WHERE tb.table_schema = 'public' ";
|
try (PreparedStatement pStmt = connect.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;
|
}
|
|
public static List<Map<String, Object>> getColumns(Connection connect, String tableName) {
|
List<Map<String, Object>> result = new ArrayList<>();
|
String sql = "SELECT col.table_name AS objName, col.column_name AS name, col.udt_name AS type, col.character_maximum_length AS LENGTH, des.description,\n" +
|
"col.numeric_precision, \n" +
|
"col.numeric_scale,\n" +
|
"col.datetime_precision,\n" +
|
"CASE is_identity WHEN 'YES' THEN 1 ELSE 0 END AS isIdentity,\n" +
|
"CASE col.IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS isNullable,\n" +
|
"col.column_default AS default\n" +
|
"FROM information_schema.columns col \n" +
|
"LEFT JOIN pg_description des ON col.table_name::regclass = des.objoid AND col.ordinal_position = des.objsubid\n" +
|
"WHERE table_name = ? " +
|
"AND table_schema = 'public' " +
|
"ORDER BY " +
|
"ordinal_position;";
|
try (PreparedStatement pStmt = connect.prepareStatement(sql)) {
|
pStmt.setString(1, tableName);
|
// pStmt.setString(2, "public");
|
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;
|
}
|
|
public static String getJavaType(String typeName) {
|
String result = "String";
|
switch (typeName) {
|
case "int2":
|
case "int4":
|
case "integer":
|
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 "int8":
|
case "bigint":
|
result = "Long";
|
break;
|
case "date":
|
result = "Date";
|
break;
|
|
default:
|
break;
|
}
|
return result;
|
}
|
|
public 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();
|
}
|
}
|
|
public static String toDBValue(Object value) {
|
String result;
|
if (null == value) {
|
return "";
|
}
|
if (value instanceof Number || value instanceof Boolean) {
|
result = value.toString();
|
} else if (value instanceof Timestamp) {
|
result = String.valueOf(((Timestamp) value).getTime());
|
} else if (value instanceof LocalDateTime) {
|
result = "'" + LocalDateTimeUtil.toFormatFullString((LocalDateTime) value) + "'";
|
} else if (value instanceof LocalDate) {
|
result = "'" + LocalDateTimeUtil.toFormatString((LocalDate) value) + "'";
|
} else if (value instanceof Date) {
|
result = "'" + LocalDateTimeUtil.toFormatFullString(((Date) value).getTime()) + "'";
|
} else if (value instanceof Calendar) {
|
result = "'" + CalendarUtil.toDateTimeMSStr((Calendar) value) + "'";
|
} else {
|
result = "'" + value.toString() + "'";
|
}
|
return result;
|
}
|
|
public static List<String> genTable(String tableName, String tableDesc, List<Map<String, Object>> listColumn, Map<String, String> mapPK, Map<String, String> mapIndex) {
|
List<String> list = new ArrayList<>();
|
|
String sql = "CREATE TABLE \"public\".\"" + tableName + "\" (\n";
|
|
Map<String, String> mapColumnDesc = new HashMap<>();
|
int idx = 0;
|
|
list.add("-- " + tableName + " - " + tableDesc + "\nDROP TABLE IF EXISTS \"public\".\"" + tableName + "\";\n");
|
|
// 遍历列,构建sql
|
for (Map<String, Object> column : listColumn) {
|
idx++;
|
String name = column.get("name").toString();
|
String type = column.get("type").toString();
|
Object desc = column.get("description");
|
Object isNullable = column.get("isNullable");
|
|
mapColumnDesc.put(name, ParameterUtil.dealNullStr(desc));
|
|
sql += "\t\"" + name + "\" " + GenCodeGauss.dbType2Gauss(type);
|
switch (type) {
|
case "char":
|
case "varchar":
|
case "nvarchar":
|
if (Objects.nonNull(column.get("length"))) {
|
String length = column.get("length").toString();
|
sql += "(" + length + ")";
|
}
|
if ("1".equals(isNullable)) {
|
sql += " NULL DEFAULT NULL";
|
} else {
|
sql += " NOT NULL DEFAULT NULL::character varying";
|
}
|
break;
|
case "numeric":
|
case "decimal":
|
String numeric_precision = column.get("numeric_precision").toString();
|
String numeric_scale = column.get("numeric_scale").toString();
|
sql += "(" + numeric_precision + "," + numeric_scale + ")";
|
if ("1".equals(isNullable)) {
|
sql += " NULL DEFAULT NULL";
|
} else {
|
sql += " NOT NULL DEFAULT 0";
|
}
|
break;
|
case "datetime":
|
case "timestamp":
|
String datetime_precision = column.get("datetime_precision").toString();
|
sql += "(" + datetime_precision + ")";
|
if ("1".equals(isNullable)) {
|
sql += " NULL DEFAULT NULL";
|
} else {
|
sql += " NOT NULL DEFAULT pg_systimestamp()";
|
}
|
break;
|
case "int":
|
case "tinyint":
|
case "bit":
|
case "int2":
|
case "int4":
|
case "int8":
|
case "bigint":
|
if ("1".equals(isNullable)) {
|
sql += " NULL DEFAULT NULL";
|
} else {
|
sql += " NOT NULL DEFAULT 0";
|
}
|
break;
|
|
default:
|
sql += " NULL DEFAULT NULL";
|
break;
|
}
|
if (idx < listColumn.size()) {
|
sql += ",";
|
}
|
sql += "\n";
|
}
|
sql += ");\n";
|
list.add(sql);
|
sql = "";
|
|
sql += "COMMENT ON TABLE \"public\".\"" + tableName + "\" IS '" + tableDesc + "';\n";
|
// 构建字段描述sql
|
for (Map.Entry<String, String> desc : mapColumnDesc.entrySet()) {
|
sql += "COMMENT ON COLUMN \"public\".\"" + tableName + "\".\"" + desc.getKey() + "\" IS '" + desc.getValue().replace("\r\n", " ").replace("\n", " ") + "';\n";
|
}
|
list.add("-- 字段描述\n" + sql);
|
sql = "";
|
|
// 设置主键
|
if (!mapPK.isEmpty()) {
|
for (Map.Entry<String, String> key : mapPK.entrySet()) {
|
sql += "ALTER TABLE \"public\".\"" + tableName + "\" ADD CONSTRAINT \"PK_" + tableName + "\" PRIMARY KEY (\"" + key.getValue() + "\");\n";
|
}
|
}
|
sql += "ALTER TABLE \"public\".\"" + tableName + "\" ADD CONSTRAINT \"PK_" + tableName + "\" PRIMARY KEY (\"id\");\n";
|
list.add("-- 设置主键\n" + sql);
|
sql = "";
|
|
// 触发器:自动赋值最后更新时间
|
sql += "CREATE TRIGGER \"TG_" + tableName + "\" BEFORE INSERT OR UPDATE ON \"public\".\"" + tableName + "\"\n" +
|
"FOR EACH ROW\n" +
|
"EXECUTE PROCEDURE \"public\".\"update_timestamp_column\"();";
|
list.add("-- 触发器:自动赋值最后更新时间\n" + sql);
|
sql = "";
|
list.add("-- 创建索引\n");
|
// 遍历索引,构建sql
|
for (Map.Entry<String, String> index : mapIndex.entrySet()) {
|
if (!mapPK.containsKey(index.getKey())) {
|
sql += "CREATE INDEX \"" + index.getKey() + "\" ON \"public\".\"test_info\"(\"" + index.getValue() + "\");\n";
|
list.add(sql);
|
sql = "";
|
}
|
}
|
return list;
|
}
|
|
private static String dbType2Gauss(String type) {
|
String result = "";
|
switch (type) {
|
case "char":
|
case "nvarchar":
|
result = "varchar";
|
break;
|
|
case "longtext":
|
result = "text";
|
break;
|
|
case "decimal":
|
result = "numeric";
|
break;
|
case "datetime":
|
result = "timestamp";
|
break;
|
|
case "bit":
|
case "tinyint":
|
result = "int2";
|
break;
|
|
case "int":
|
result = "int4";
|
break;
|
|
default:
|
result = type;
|
break;
|
}
|
return result;
|
}
|
|
public static boolean execSql(Connection connect, String sql) {
|
try(PreparedStatement pst = connect.prepareStatement(sql)) {
|
int rowCount = pst.executeUpdate();
|
return rowCount > 0;
|
} catch (Exception e) {
|
return false;
|
}
|
}
|
|
public static Map<String, String> getPK(Connection connect, String tableName) {
|
Map<String, String> mapPK = new HashMap<>();
|
// 查询主键
|
String pkSq = "select pg_attribute.attname as col_name,pg_constraint.conname as pk_name\n" +
|
"from pg_constraint\n" +
|
"inner join pg_class on pg_constraint.conrelid=pg_class.oid\n" +
|
"inner join pg_attribute on pg_attribute.attrelid=pg_class.oid and pg_attribute.attnum=pg_constraint.conkey[1]\n" +
|
"where pg_class.relname='" + tableName + "'\n" +
|
"and pg_constraint.contype='p'";
|
try (PreparedStatement pStmt = connect.prepareStatement(pkSq)) {
|
try (ResultSet rs = pStmt.executeQuery()) {
|
//获取键名
|
ResultSetMetaData md = rs.getMetaData();
|
//获取列的数量
|
int columnCount = md.getColumnCount();
|
while (rs.next()) {
|
String pk_name = rs.getString("pk_name");
|
String col_name = rs.getString("col_name");
|
mapPK.put(pk_name, col_name);
|
}
|
}
|
} catch (Exception e) {
|
System.out.println(e);
|
}
|
return mapPK;
|
}
|
|
public static Map<String, String> getIndex(Connection connect, String tableName) {
|
Map<String, String> mapPK = new HashMap<>();
|
// 查询主键
|
String pkSq = "SELECT * FROM pg_indexes WHERE tablename = '" + tableName + "';";
|
try (PreparedStatement pStmt = connect.prepareStatement(pkSq)) {
|
try (ResultSet rs = pStmt.executeQuery()) {
|
//获取键名
|
ResultSetMetaData md = rs.getMetaData();
|
while (rs.next()) {
|
String indexname = rs.getString("indexname");
|
String indexdef = rs.getString("indexdef");
|
mapPK.put(indexname, indexdef);
|
}
|
}
|
} catch (Exception e) {
|
System.out.println(e);
|
}
|
return mapPK;
|
}
|
|
public static List<Map<String, Object>> getListAll(Connection connect, String sql) {
|
List<Map<String, Object>> result = new ArrayList<>();
|
try (PreparedStatement pStmt = connect.prepareStatement(sql)) {
|
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;
|
}
|
|
public static List<String> insertAll(List<Map<String, Object>> list, String tableName, Integer onceCount) {
|
List<String> result = new ArrayList<>();
|
String insertSql = "INSERT INTO public.\"" + tableName + "\"(\"";
|
List<String> listColumn = new ArrayList<>();
|
for (String column : list.get(0).keySet()) {
|
if ("update_time".equalsIgnoreCase(column)) {
|
continue;
|
}
|
listColumn.add("\"" + column + "\"");
|
}
|
insertSql += StringUtil.join(listColumn, "\",\"") + "\") VALUES";
|
|
String sql = "";
|
for (int i = 0; i < list.size(); i++) {
|
if (StringUtil.isNullOrEmpty(sql)) {
|
sql = insertSql;
|
}
|
Map<String, Object> row = list.get(i);
|
|
List<Object> listColValue = new ArrayList<>();
|
for (Map.Entry<String, Object> item : row.entrySet()) {
|
if ("update_time".equalsIgnoreCase(item.getKey())) {
|
continue;
|
}
|
listColValue.add(item.getValue());
|
}
|
sql += "\n(" + StringUtil.join(listColValue.stream().map(GenCodeGauss::getSqlValue).collect(Collectors.toList())) + "),";
|
|
if (i > 0 && i % onceCount == 0) {
|
sql = sql.substring(0, sql.length() - 1);
|
|
result.add(sql + ";");
|
|
sql = "";
|
}
|
}
|
if (StringUtil.isNotNullOrEmpty(sql)) {
|
sql = sql.substring(0, sql.length() - 1);
|
|
result.add(sql + ";");
|
}
|
return result;
|
}
|
private static String getSqlValue(Object value) {
|
if (Objects.isNull(value)) {
|
return "null";
|
}
|
if (value instanceof String) {
|
return "'" + value + "'";
|
}
|
if (value instanceof Date) {
|
return "'" + LocalDateTimeUtil.toFormatFullString(((Date)value).getTime()) + "'";
|
}
|
if (value instanceof LocalDate) {
|
return "'" + LocalDateTimeUtil.toFormatString((LocalDate)value) + "'";
|
}
|
if (value instanceof LocalDateTime) {
|
return "'" + LocalDateTimeUtil.toFormatFullString((LocalDateTime)value) + "'";
|
}
|
if (value instanceof Calendar) {
|
return "'" + CalendarUtil.toDateTimeMSStr((Calendar)value) + "'";
|
}
|
return value.toString();
|
}
|
|
public static String getAutoUpdateTimeFunction() {
|
return "CREATE OR REPLACE FUNCTION \"public\".\"update_timestamp_column\"()\n" +
|
" RETURNS \"pg_catalog\".\"trigger\" AS $BODY$\n" +
|
"BEGIN\n" +
|
"NEW.update_time := current_timestamp;\n" +
|
"RETURN NEW;\n" +
|
"END;\n" +
|
"$BODY$\n" +
|
" LANGUAGE plpgsql VOLATILE\n" +
|
" COST 100";
|
}
|
|
public static List<String> export(Connection connect, String dbSchema, boolean isData, boolean isAutoUpdateTimeFunc) {
|
List<String> listTable = new ArrayList<>();
|
List<String> listData = new ArrayList<>();
|
if (isAutoUpdateTimeFunc) {
|
listTable.add(GenCodeGauss.getAutoUpdateTimeFunction());
|
}
|
// 获取所有表
|
Map<String, String> tables = GenCodeGauss.getTables(connect, dbSchema);
|
// 遍历所有表
|
for (Map.Entry<String, String> table : tables.entrySet()) {
|
String tabName = table.getKey();
|
String tabDesc = table.getValue();
|
|
// 获取所有列
|
List<Map<String, Object>> listCol = GenCodeGauss.getColumns(connect, tabName);
|
|
Map<String, String> mapPK = GenCodeGauss.getPK(connect, tabName);
|
|
Map<String, String> mapIndex = GenCodeGauss.getIndex(connect, tabName);
|
|
// 生成表的sql
|
List<String> listGenTable = GenCodeGauss.genTable(tabName, tabDesc, listCol, mapPK, mapIndex);
|
listTable.addAll(listGenTable);
|
|
if (isData) {
|
// 获取mysql表所有数据
|
String sqlSelect = "SELECT * FROM " + table.getKey();
|
Integer count = 1;
|
Integer pageSize = ConstantFactory.NUM500;
|
String orderBy = "id";
|
Object lastId = null;
|
while (count > 0) {
|
count = 0;
|
String sql = sqlSelect + (Objects.isNull(lastId) ? "" : " WHERE " + orderBy + " > " + GenCodeGauss.toDBValue(lastId) + "") + " ORDER BY " + orderBy + " LIMIT " + pageSize;
|
List<Map<String, Object>> list = GenCodeGauss.getListAll(connect, sql);
|
if (ListUtil.isNullOrEmpty(list)) {
|
continue;
|
}
|
count = list.size();
|
lastId = list.get(list.size() - 1).get(orderBy);
|
|
// 批量插入gauss数据库
|
List<String> insertAll = GenCodeGauss.insertAll(list, table.getKey(), ConstantFactory.NUM50);
|
listData.add(StringUtil.join(insertAll, "\n"));
|
}
|
}
|
}
|
if (ListUtil.isNotNullOrEmpty(listData)) {
|
listTable.addAll(listData);
|
}
|
return listTable;
|
}
|
public static List<String> export(Connection connect, String dbSchema) {
|
return GenCodeGauss.export(connect, dbSchema, Boolean.TRUE, Boolean.TRUE);
|
}
|
}
|