| | |
| | | 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 com.lunhan.xxx.common.util.*; |
| | | import org.apache.commons.lang3.BooleanUtils; |
| | | |
| | | import java.io.File; |
| | |
| | | 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 = "test_db1"; |
| | | private static final String DB_NAME = "water_basic"; |
| | | private static final String AUTHOR = "lin.liu"; |
| | | |
| | | private static Connection CONN = null; |
| | | 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; |
| | | |
| | |
| | | private static final Integer SET_PO_Getter = 1; |
| | | //endregion |
| | | |
| | | //region po类头部文字设置 |
| | | //region 类头部文字设置 |
| | | private static final String SET_BEFORE_TEXT = |
| | | "/**\n" + |
| | | "# __----~~~~~~~~~~~------___\n" + |
| | |
| | | "*/"; |
| | | //endregion |
| | | |
| | | //region import依赖架包 |
| | | |
| | | //region po类 import 内容设置 |
| | | private static final String[] SET_PO_IMPORT = new String[]{ |
| | | "import com.baomidou.mybatisplus.annotation.*;", |
| | |
| | | }; |
| | | //endregion |
| | | |
| | | //region 实体映射类 import 内容设置 |
| | | //region 实体属性映射类 import 内容设置 |
| | | private static final String[] SET_CONVERT_IMPORT = new String[]{ |
| | | "import org.mapstruct.Mapper;" + |
| | | "import org.mapstruct.factory.Mappers;" + |
| | |
| | | }; |
| | | //endregion |
| | | |
| | | //region dao类 import 内容设置 |
| | | private static final String[] SET_DAO_IMPORT = new String[]{ |
| | | //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.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.SearchBasicDTO;", |
| | | "import com.lunhan.xxx.entity.enums.EOrderBy;", |
| | | "import com.lunhan.xxx.common.util.*;", |
| | | "import com.lunhan.xxx.entity.dto.*;", |
| | | "import com.lunhan.xxx.entity.enums.*;", |
| | | "import com.lunhan.xxx.repository.BasicMapperImpl;", |
| | | "import org.springframework.stereotype.Repository;" |
| | | }; |
| | |
| | | }; |
| | | //endregion |
| | | |
| | | //endregion |
| | | |
| | | //region 类注释模版 |
| | | private static final String SET_CLASS_DESC_TPL = |
| | | "/**\n" + |
| | |
| | | //#endregion |
| | | |
| | | //#region 编辑接口忽略字段配置 |
| | | private static final List<String> NO_UPDATE_COLUMNS = Arrays.asList( |
| | | 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( |
| | | private static final List<String> UPDATE_TIME_COLUMNS = Arrays.asList( |
| | | "update_time", "datachange_lasttime", "data_change_last_time" |
| | | ); |
| | | //#endregion |
| | |
| | | * 只生成以下配置的表 |
| | | */ |
| | | private static final List<String> ONLY_TABLES = Arrays.asList( |
| | | "water_meter_apply" |
| | | |
| | | ); |
| | | |
| | | public static void main(String[] args) { |
| | |
| | | System.out.println("conn is null."); |
| | | return; |
| | | } |
| | | Map<String, String> tables = getTables(DB_NAME); |
| | | Map<String, String> tables = getTables(CONN, DB_NAME); |
| | | for (Map.Entry<String, String> table : tables.entrySet()) { |
| | | String tableName = table.getKey(); |
| | | String tableDesc = table.getValue(); |
| | |
| | | if (ONLY_TABLES.size() > 0 && BooleanUtils.isFalse(ONLY_TABLES.contains(tableName))) { |
| | | continue; |
| | | } |
| | | List<Map<String, Object>> columns = getColumns(tableName, DB_NAME); |
| | | 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); |
| | | genDao(tableName, tableDesc); |
| | | genMapperImpl(tableName, tableDesc); |
| | | genConvertMapper(tableName, tableDesc); |
| | | genService(tableName, tableDesc); |
| | | genController(tableName, tableDesc); |
| | |
| | | listColumn.add("(type = IdType.ASSIGN_ID)"); |
| | | } |
| | | } |
| | | String columnAnnotation = "\t@TableField(\"" + name + "\""; |
| | | //忽略最后修改时间这一列的新增和编辑 |
| | | if (!"id".equals(name)) { |
| | | String columnAnnotation = "\t@TableField(\"" + 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(columnAnnotation + ")"); |
| | | //追加列 |
| | | listColumn.add(String.format("\tprivate %s %s;", javaType, propName)); |
| | | |
| | |
| | | } |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : tableDesc) |
| | | .replaceAll("\\{\\#\\=author\\}", AUTHOR) |
| | | .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) |
| | | ); |
| | |
| | | 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); |
| | | 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()); |
| | |
| | | |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .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(ConstantFactory.STR_NEWLINE); |
| | | content.append("public class "); |
| | |
| | | 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(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .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); |
| | | 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}"); |
| | | 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("}"); |
| | | |
| | |
| | | writeFile(GenCodeGauss.OutSet.SEARCH + "/", searchName + ".java", content.toString()); |
| | | } |
| | | |
| | | private static void genDao(String tableName, String tableDesc) { |
| | | 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; |
| | |
| | | content.append(GenCodeGauss.PackageSet.MAPPER_IMPL); |
| | | content.append(ConstantFactory.STR_SEMICOLON); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | if (SET_DAO_IMPORT.length > 0) { |
| | | if (SET_MAPPER_IMPL_IMPORT.length > 0) { |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | for (String s : SET_DAO_IMPORT) { |
| | | for (String s : SET_MAPPER_IMPL_IMPORT) { |
| | | content.append(s); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | } |
| | |
| | | content.append(poName + ";\n"); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : tableDesc) |
| | | .replaceAll("\\{\\#\\=author\\}", AUTHOR) |
| | | .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) |
| | | ); |
| | |
| | | content.append(daoName); |
| | | content.append(" extends BasicMapperImpl<"); |
| | | content.append(modelName + GenCodeGauss.SuffixSet.PO); |
| | | content.append("> {"); |
| | | 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(" + searchName + " request) {\n" + |
| | | "\tpublic PagerResult<" + poName + "> search(SearchBasicDTO request) {\n" + |
| | | "\t\t// 还原查询条件真实类型\n" + |
| | | "\t\t" + searchName + " search = (" + searchName + ")request;\n" + |
| | | "\t\t// 查询条件\n" + |
| | |
| | | "\t\t// 数据创建时间-截止\n" + |
| | | "\t\tqueryWrapper.le(NumericUtil.tryParseLong(search.getCreateTimeEnd()).compareTo(0L) > 0, " + poName + "::getCreateTime, search.getCreateTimeEnd());\n" + |
| | | "\t\t// 关键字\n" + |
| | | "\t\tif (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" + |
| | | "\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\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\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.orderByAsc(" + poName + "::getCreateTime);\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.orderByAsc(" + poName + "::getUpdateTime);\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} else {\n" + |
| | | "\t\t\tqueryWrapper.orderByDesc(" + poName + "::getId);\n" + |
| | | "\t\t}\n" + |
| | | "\t\tPage<" + poName + "> pageResult = DB.selectPage(new Page<>(search.getPage(), search.getLimit()), queryWrapper);\n" + |
| | | "\t\tPage<" + poName + "> pageResult = super.selectPage(new Page<>(search.getPage(), search.getLimit()), queryWrapper);\n" + |
| | | "\t\treturn new PagerResult<>(pageResult.getSize(), pageResult.getPages(), pageResult.getTotal(), pageResult.getRecords());\n" + |
| | | "\t}"); |
| | | "\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()) { |
| | |
| | | } |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .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(ConstantFactory.STR_NEWLINE); |
| | | content.append("public class "); |
| | |
| | | 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); |
| | | if (!isData) { |
| | | content.append(StringUtil.join(listGetterSetter, ConstantFactory.STR_NEWLINE)); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | } |
| | | content.append("}"); |
| | | |
| | | if (new File(GenCodeGauss.OutSet.RequestDTO + tableNamePackage + "/" + createDTOName + ".java").exists()) { |
| | |
| | | } |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .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(ConstantFactory.STR_NEWLINE); |
| | | content.append("public class "); |
| | |
| | | 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); |
| | | if (!isData) { |
| | | content.append(StringUtil.join(listGetterSetter, ConstantFactory.STR_NEWLINE)); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | } |
| | | content.append("}"); |
| | | |
| | | if (new File(GenCodeGauss.OutSet.RequestDTO + tableNamePackage + "/" + modifyDTOName + ".java").exists()) { |
| | |
| | | |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : tableDesc) |
| | | ); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append("@Mapper"); |
| | |
| | | content.append(responseDTOName + ";\n"); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : tableDesc) |
| | | .replaceAll("\\{\\#\\=author\\}", AUTHOR) |
| | | .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) |
| | | ); |
| | |
| | | content.append(serviceName); |
| | | content.append(" extends BaseService {\n"); |
| | | content.append(" @Autowired\n" + |
| | | " private " + daoName + " dao;\n"); |
| | | " private " + daoName + " mapper;\n"); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(" public ExecutedResult<Long> create(" + createDTOName + " request) {\n" + |
| | | " // 转换po\n" + |
| | |
| | | " // 设置记录创建时间\n" + |
| | | " item.setCreateTime(LocalDateTimeUtil.nowTimeStamp());\n" + |
| | | " // 是否删除(逻辑删除)初始值\n" + |
| | | " //item.setIsDelete(EYesOrNo.NO.getValue());\n" + |
| | | " item.setIsDelete(EYesOrNo.NO.getValue());\n" + |
| | | "\n" + |
| | | " Boolean result = this.dao.add(item);\n" + |
| | | " if (BooleanUtils.isFalse(result)) {\n" + |
| | | " int rowCount = mapper.insert(item);\n" + |
| | | " if (rowCount != 1) {\n" + |
| | | " return ExecutedResult.failed(\"创建[" + tableDesc + "]失败。\");\n" + |
| | | " }\n" + |
| | | " return ExecutedResult.success(item.getId());\n" + |
| | |
| | | " // 转换po\n" + |
| | | " " + poName + " item = CopierUtil.mapTo(request, " + poName + ".class);\n" + |
| | | "\n" + |
| | | " Boolean result = this.dao.modify(item);\n" + |
| | | " if (BooleanUtils.isFalse(result)) {\n" + |
| | | " int rowCount = mapper.updateById(item);\n" + |
| | | " if (rowCount != 1) {\n" + |
| | | " return ExecutedResult.failed(\"编辑[" + tableDesc + "]失败。\");\n" + |
| | | " }\n" + |
| | | " return ExecutedResult.success();\n" + |
| | |
| | | " public ExecutedResult<" + responseDTOName + "> get(Long id) {\n" + |
| | | " " + responseDTOName + " result = new " + responseDTOName + "();\n" + |
| | | "\n" + |
| | | " " + poName + " find = dao.getById(id);\n" + |
| | | " " + poName + " find = mapper.get(id);\n" + |
| | | " if (null != find) {\n" + |
| | | " result = CopierUtil.mapTo(find, " + responseDTOName + ".class);\n" + |
| | | " }\n" + |
| | |
| | | "// item.setId(id);\n" + |
| | | "// item.setStatus(EState.DISABLED.getValue());\n" + |
| | | "//\n" + |
| | | "// Boolean result = this.dao.modify(item);\n" + |
| | | "// if (BooleanUtils.isFalse(result)) {\n" + |
| | | "// int rowCount = mapper.updateById(item);\n" + |
| | | "// if (rowCount != 1) {\n" + |
| | | "// return ExecutedResult.failed(\"停用[" + tableDesc + "]失败。\");\n" + |
| | | "// }\n" + |
| | | "// return ExecutedResult.success();\n" + |
| | |
| | | "// item.setId(id);\n" + |
| | | "// item.setStatus(EState.NORMAL.getValue());\n" + |
| | | "//\n" + |
| | | "// Boolean result = this.dao.modify(item);\n" + |
| | | "// if (BooleanUtils.isFalse(result)) {\n" + |
| | | "// int rowCount = mapper.updateById(item);\\n\" +\n" + |
| | | "// if (rowCount != 1) {\n" + |
| | | "// return ExecutedResult.failed(\"启用[" + tableDesc + "]失败。\");\n" + |
| | | "// }\n" + |
| | | "// return ExecutedResult.success();\n" + |
| | |
| | | "// item.setId(request.getId());\n" + |
| | | "// item.setSort(request.getSort());\n" + |
| | | "//\n" + |
| | | "// Boolean result = this.dao.modify(item);\n" + |
| | | "// if (BooleanUtils.isFalse(result)) {\n" + |
| | | "// int rowCount = mapper.updateById(item);\\n\" +\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 = this.dao.remove(id);\n" + |
| | | "// Boolean result = mapper.deleteLogic(id);\n" + |
| | | "// if (BooleanUtils.isFalse(result)) {\n" + |
| | | "// return ExecutedResult.failed(\"删除[" + tableDesc + "]失败。\");\n" + |
| | | "// }\n" + |
| | |
| | | "// }\n" + |
| | | "//\n" + |
| | | "// public ExecutedResult<String> removeList(List<Long> ids) {\n" + |
| | | "// Boolean result = this.dao.removeByListId(ids);\n" + |
| | | "// Boolean result = mapper.deleteLogic(ids);\n" + |
| | | "// if (BooleanUtils.isFalse(result)) {\n" + |
| | | "// return ExecutedResult.failed(\"删除[" + tableDesc + "]失败。\");\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" + |
| | | " List<" + poName + "> list = mapper.getList(listId);\n" + |
| | | " if (ListUtil.isNotNullOrEmpty(list)) {\n" + |
| | | " result = CopierUtil.mapTo(list, " + responseDTOName + ".class);\n" + |
| | | " }\n" + |
| | |
| | | " search.setCreateTimeEnd(LocalDateTimeUtil.getTimeStamp(createTimeRange.getItem2()).getTime());\n" + |
| | | " }\n" + |
| | | "\n" + |
| | | " PagerResult<" + poName + "> pageList = dao.search(search);\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" + |
| | |
| | | " }\n" + |
| | | "\n" + |
| | | " protected ExecutedResult<" + poName + "> check4Id(Long id) {\n" + |
| | | " " + poName + " exists = dao.getById(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"); |
| | | " }\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()) { |
| | |
| | | content.append(responseDTOName + ";\n"); |
| | | content.append(ConstantFactory.STR_NEWLINE); |
| | | content.append(SET_CLASS_DESC_TPL |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc) |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : tableDesc) |
| | | .replaceAll("\\{\\#\\=author\\}", AUTHOR) |
| | | .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) |
| | | ); |
| | |
| | | .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" + |
| | |
| | | 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 + " mapper") |
| | | .replaceAll("\\{\\#\\=desc\\}", tableDesc == null ? modelName : tableDesc + " mapper") |
| | | .replaceAll("\\{\\#\\=author\\}", AUTHOR) |
| | | .replaceAll("\\{\\#\\=date\\}", LocalDateTimeUtil.todayStr().replaceAll("\\-", "/")) |
| | | ); |
| | |
| | | //#endregion |
| | | |
| | | |
| | | private static Map<String, String> getTables(String dbSchema) { |
| | | 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" + |
| | |
| | | " 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 = CONN.prepareStatement(sql)) { |
| | | try (PreparedStatement pStmt = connect.prepareStatement(sql)) { |
| | | //pStmt.setString(1, dbSchema); |
| | | try (ResultSet rs = pStmt.executeQuery()) { |
| | | while (rs.next()) { |
| | |
| | | return result; |
| | | } |
| | | |
| | | private static List<Map<String, Object>> getColumns(String tableName, String dbSchema) { |
| | | 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.data_type AS type, " + |
| | | "col.character_maximum_length AS LENGTH, " + |
| | | "des.description, " + |
| | | "col.numeric_precision, " + |
| | | "col.numeric_scale," + |
| | | "CASE is_identity WHEN 'YES' THEN 1 ELSE 0 END AS isIdentity, " + |
| | | "CASE col.IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS isNullable, " + |
| | | "col.column_default AS default " + |
| | | "from " + |
| | | "information_schema.columns col left join pg_description des on " + |
| | | "col.table_name::regclass = des.objoid " + |
| | | "and col.ordinal_position = des.objsubid " + |
| | | "where " + |
| | | "table_name = ? " + |
| | | "and table_schema = 'public' " + |
| | | "order by " + |
| | | 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 = CONN.prepareStatement(sql)) { |
| | | try (PreparedStatement pStmt = connect.prepareStatement(sql)) { |
| | | pStmt.setString(1, tableName); |
| | | // pStmt.setString(2, "public"); |
| | | try (ResultSet rs = pStmt.executeQuery()) { |
| | |
| | | return result; |
| | | } |
| | | |
| | | private static String getJavaType(String typeName) { |
| | | public static String getJavaType(String typeName) { |
| | | String result = "String"; |
| | | switch (typeName) { |
| | | case "int2": |
| | | case "int4": |
| | | case "integer": |
| | | case "tinyint": |
| | | result = "Integer"; |
| | |
| | | case "decimal": |
| | | result = "BigDecimal"; |
| | | break; |
| | | case "int8": |
| | | case "bigint": |
| | | result = "Long"; |
| | | break; |
| | |
| | | return result; |
| | | } |
| | | |
| | | private static String underline2Camel(String line, boolean... firstIsUpperCase) { |
| | | public static String underline2Camel(String line, boolean... firstIsUpperCase) { |
| | | String str = ""; |
| | | if (StringUtil.isNullOrEmpty(line)) { |
| | | return str; |
| | |
| | | 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 boolean genTable(Connection connect, String tableName, String tableDesc, List<Map<String, Object>> listColumn, Map<String, String> mapPK, Map<String, String> mapIndex) throws SQLException { |
| | | String sql = "CREATE TABLE \"public\".\"" + tableName + "\" (\n"; |
| | | |
| | | Map<String, String> mapColumnDesc = new HashMap<>(); |
| | | int idx = 0; |
| | | boolean result = Boolean.FALSE; |
| | | |
| | | result = GenCodeGauss.execSql(connect, "DROP 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(); |
| | | String desc = column.get("description").toString(); |
| | | String isNullable = column.get("isNullable").toString(); |
| | | |
| | | mapColumnDesc.put(name, desc); |
| | | |
| | | sql += "\t\"" + name + "\" " + GenCodeGauss.mysqlType2Gauss(type); |
| | | switch (type) { |
| | | case "char": |
| | | case "varchar": |
| | | case "nvarchar": |
| | | 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" + |
| | | ";\n"; |
| | | result = GenCodeGauss.execSql(connect, 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"; |
| | | } |
| | | result = GenCodeGauss.execSql(connect, 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"; |
| | | result = GenCodeGauss.execSql(connect, 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\"();"; |
| | | result = GenCodeGauss.execSql(connect, sql); |
| | | sql = ""; |
| | | |
| | | // 遍历索引,构建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"; |
| | | result = GenCodeGauss.execSql(connect, sql); |
| | | sql = ""; |
| | | } |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | private static String mysqlType2Gauss(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 tableName, String dbSchema) { |
| | | List<Map<String, Object>> result = new ArrayList<>(); |
| | | String sql = "SELECT * FROM " + dbSchema + "." + tableName; |
| | | 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<Boolean> insertAll(Connection connect, List<Map<String, Object>> list, String tableName, Integer onceCount) { |
| | | List<Boolean> 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 = ""; |
| | | List<Object> listValue = new ArrayList<>(); |
| | | 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(c -> "?").collect(Collectors.toList())) + "),"; |
| | | listValue.addAll(listColValue); |
| | | if (i > 0 && i % onceCount == 0) { |
| | | sql = sql.substring(0, sql.length() - 1); |
| | | try (PreparedStatement pStmt = connect.prepareStatement(sql)) { |
| | | for (int j = 0; j < listValue.size(); j++) { |
| | | pStmt.setObject(j + 1, listValue.get(j)); |
| | | } |
| | | listValue = new ArrayList<>(); |
| | | boolean insertList = pStmt.execute(); |
| | | result.add(insertList); |
| | | System.out.println("插入数据" + Math.max(i - onceCount, 0) + " - " + i + ",结果:" + insertList); |
| | | } catch (SQLException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | sql = ""; |
| | | } |
| | | } |
| | | if (StringUtil.isNotNullOrEmpty(sql)) { |
| | | sql = sql.substring(0, sql.length() - 1); |
| | | try (PreparedStatement pStmt = connect.prepareStatement(sql)) { |
| | | for (int j = 0; j < listValue.size(); j++) { |
| | | Object value = listValue.get(j); |
| | | if (Objects.equals("", value)) { |
| | | // TODO 神奇的gauss,''会判定为null,如果有非空约束,会插入失败 |
| | | value = " "; |
| | | } |
| | | pStmt.setObject(j + 1, value); |
| | | } |
| | | listValue = new ArrayList<>(); |
| | | boolean insertList = pStmt.execute(); |
| | | result.add(insertList); |
| | | System.out.println("插入数据" + (list.size() - list.size() % onceCount) + " - " + list.size() + ",结果:" + insertList); |
| | | } catch (SQLException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | return result; |
| | | } |
| | | } |