fanxp il y a 1 an
Parent
commit
37d1d1b275

+ 1 - 0
.gitignore

@@ -1,6 +1,7 @@
 HELP.md
 target/
 logs/
+generator/
 !.mvn/wrapper/maven-wrapper.jar
 !**/src/main/**/target/
 !**/src/test/**/target/

+ 1 - 1
Makefile

@@ -2,7 +2,7 @@ merge:
 	git checkout master;git merge dev;git push;git checkout dev;
 
 create-tag:
-	git checkout master;git tag v1.0.1;git push origin --tags;git checkout dev;
+	git checkout master;git tag v1.0.5;git push origin --tags;git checkout dev;
 
 remove-tag:
 	git tag -d v1.0.1;git push origin :refs/tags/v1.0.1;

+ 5 - 2
src/main/java/com/xjrsoft/common/factory/MinioService.java

@@ -42,8 +42,11 @@ public class MinioService extends CloudStorageService {
         } catch (Exception e){
             throw new RuntimeException("上传文件失败,请检查配置信息", e);
         }
-
-        return config.getEndpoint() + StringPool.SLASH + config.getBucketName() +  StringPool.SLASH + path;
+        if (!config.getEndpointPreview().isEmpty()){
+            return config.getEndpointPreview() + StringPool.SLASH + config.getBucketName() +  StringPool.SLASH + path;
+        }else{
+            return config.getEndpoint() + StringPool.SLASH + config.getBucketName() +  StringPool.SLASH + path;
+        }
     }
 
     @Override

+ 5 - 0
src/main/java/com/xjrsoft/config/OSSConfig.java

@@ -29,6 +29,11 @@ public class OSSConfig {
      */
      private String endpoint;
 
+    /**
+     * 预览域名
+     */
+    private String endpointPreview;
+
     /**
      * 前缀
      */

+ 1 - 0
src/main/java/com/xjrsoft/module/system/controller/FileController.java

@@ -192,6 +192,7 @@ public class FileController {
         //保存到云服务器
         String filePath = UploadUtil.uploadFile(multipartFile);
 
+
         File file = new File();
         file.setId(fileId);
         file.setFolderId(folderId);

+ 1 - 1
src/main/java/com/xjrsoft/module/system/service/impl/SaOAuth2TemplateImpl.java

@@ -29,7 +29,7 @@ public class SaOAuth2TemplateImpl extends SaOAuth2Template {
     @Override
     public String getOpenid(String clientId, Object loginId) {
         // 此为模拟数据,真实环境需要从数据库查询
-        return "gr_SwoIN0MC1ewxHX_vfCW3BothWDZMMtx__";
+        return "";
     }
 
     // 重写 Access-Token 生成策略:复用登录会话的Token

+ 66 - 0
src/main/resources/apiTemplates/entity.java.ftl

@@ -0,0 +1,66 @@
+package ${package};
+
+import com.baomidou.mybatisplus.annotation.FieldFill;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableLogic;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.github.yulichang.annotation.EntityMapping;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import java.io.Serializable;
+import java.time.LocalTime;
+import java.time.LocalDateTime;
+import java.math.BigDecimal;
+import java.util.List;
+
+
+/**
+* @title: ${tableComment}
+* @Author ${author}
+* @Date: ${date}
+* @Version 1.0
+*/
+@Data
+@TableName("${tableName}")
+@ApiModel(value = "${tableComment}对象", description = "${tableComment}")
+public class ${entityClass} implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+<#--属性遍历-->
+<#list fields as field>
+    /**
+    * ${field.fieldComment}
+    */
+    @ApiModelProperty("${field.fieldComment}")
+    <#if field.autoInsert?? >
+    @TableField(fill = FieldFill.INSERT)
+    </#if>
+    <#if field.autoUpdate?? >
+    @TableField(fill = FieldFill.UPDATE)
+    </#if>
+    <#if field.deleteMark?? >
+    @TableLogic
+    </#if>
+    <#if field.pk>
+    @TableId
+    </#if>
+    private ${field.fieldType} ${field.fieldName};
+</#list>
+
+<#--子表遍历-->
+<#if childTables?? >
+<#list childTables as childTable>
+    /**
+    * ${childTable.tableName}
+    */
+    @ApiModelProperty("${childTable.tableName}子表")
+    @TableField(exist = false)
+    @EntityMapping(thisField = "${childTable.relationTableField}", joinField = "${childTable.relationField}")
+    private List<${childTable.tableName?cap_first}> ${childTable.tableName}List;
+</#list>
+</#if>
+
+}

+ 1 - 0
src/main/resources/application-dev.yml

@@ -51,6 +51,7 @@ xjrsoft:
     access-key: ycbx
     secret-key: qwe123QWE
     endpoint: https://test.minio.yingcaibx.com
+    endpoint-preview: https://test.minio.yingcaibx.com
     bucket-name: learun
     prefix: xjr
   generate:

+ 2 - 1
src/main/resources/application-prod.yml

@@ -51,7 +51,8 @@ xjrsoft:
     access-key: 2LHjFEvzGaSTw7vt
     secret-key: taHsgYz9hk7ZrQZD
     endpoint: http://219.153.208.41:9000
-    bucket-name: tl
+    endpoint-preview: https://zhxy.cqtlzjzx.com/minio
+    bucket-name: static
     prefix: xjr
   generate:
     webPath: E:\code\font\xjrsoft-vue3 #生成代码的路径

+ 16 - 5
src/test/java/com/xjrsoft/xjrsoftboot/CodeGenerator.java

@@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.generator.FastAutoGenerator;
 import com.baomidou.mybatisplus.generator.config.OutputFile;
 import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
 
+import java.io.File;
 import java.sql.Array;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -18,14 +19,14 @@ class CodeGenerator {
 
     public static void main(String[] args) {
 
-        final String dbUrl = "jdbc:mysql://192.168.0.124:3306/tzx_test?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true"; //数据库连接地址
+        final String dbUrl = "jdbc:mysql://8.142.26.206:3306/tl?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true"; //数据库连接地址
         final String dbUserName = "root";//数据库账号
-        final String dbPassword = "Xjrsoft9012@@"; //数据库密码
+        final String dbPassword = "Zwr~-f6H,u6QE^]C-AD_"; //数据库密码
         final String authorName = "tzx";// 设置作者
         final String outputDir = getOutputDir(); // 指定输出目录
         final String parentModuleName = "com.xjrsoft.module";// 设置父包名
         final String moduelName = "print";// 设置父包模块名
-        final List<String> tableNames = ListUtil.toList("xjr_print_config"); //所需要生成 的表名称 可以多个
+        final List<String> tableNames = ListUtil.toList("base_class", "base_semester","base_course_subject"); //所需要生成 的表名称 可以多个
         final List<String> prefixs = ListUtil.toList("xjr_"); //所需要忽略的前缀 可以多个
 
         //拼接设置mapperXml生成路径
@@ -50,7 +51,7 @@ class CodeGenerator {
                     builder.addInclude(tableNames) // 设置需要生成的表名
                             .addTablePrefix(prefixs); // 设置过滤表前缀
                 })
-                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
+//                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                 .execute();
     }
 
@@ -58,7 +59,17 @@ class CodeGenerator {
      * 获取生成目录 默认生成到src/main/java/com/xjrsoft/module
      */
     private static String getOutputDir() {
-        return System.getProperty("user.dir") + StringPool.SLASH + "src" + StringPool.SLASH + "main" + StringPool.SLASH + "java";
+        String outDir = System.getProperty("user.dir") + StringPool.SLASH + "generator" + StringPool.SLASH + "main" + StringPool.SLASH + "java";
+        File folder = new File(outDir);
+
+        if (!folder.exists()) {
+            if (folder.mkdirs()) {
+                System.out.println("The folder is created successfully.");
+            } else {
+                System.out.println("Failed to create the folder.");
+            }
+        }
+        return outDir;
     }
 
 

+ 215 - 0
src/test/java/com/xjrsoft/xjrsoftboot/FreeMarkerGeneratorTest.java

@@ -0,0 +1,215 @@
+package com.xjrsoft.xjrsoftboot;
+
+import cn.dev33.satoken.secure.SaSecureUtil;
+import cn.hutool.core.bean.BeanUtil;
+import cn.hutool.core.util.StrUtil;
+import cn.hutool.db.meta.Column;
+import cn.hutool.db.meta.MetaUtil;
+import cn.hutool.db.meta.Table;
+import cn.hutool.http.HttpUtil;
+import com.baomidou.mybatisplus.core.toolkit.StringPool;
+import com.xjrsoft.XjrSoftApplication;
+import com.xjrsoft.common.constant.GlobalConstant;
+import com.xjrsoft.common.utils.DatasourceUtil;
+import com.xjrsoft.common.utils.JdbcToJavaUtil;
+import com.xjrsoft.module.generator.constant.EntityConstant;
+import com.xjrsoft.module.generator.dto.ApiGenerateCodesDto;
+import com.xjrsoft.module.generator.entity.FieldConfig;
+import com.xjrsoft.module.generator.entity.GeneratorConfig;
+import com.xjrsoft.module.generator.entity.TableConfig;
+import com.xjrsoft.module.generator.service.IApiGeneratorService;
+import freemarker.template.Template;
+import freemarker.template.TemplateException;
+import lombok.AllArgsConstructor;
+import org.junit.jupiter.api.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
+import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
+
+import java.io.IOException;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.*;
+import java.util.stream.Collectors;
+
+@SpringBootTest(classes = XjrSoftApplication.class)
+public class FreeMarkerGeneratorTest {
+
+    private static final String ENTITY_TEMPLATE_NAME = "entity.java.ftl";
+
+    @Autowired
+    private FreeMarkerConfigurer freeMarkerConfigurer;
+
+    @Autowired
+    private IApiGeneratorService apiGeneratorService;
+
+    @Test
+    public void generateCodesTest(){
+        List<TableConfig> tableConfigs = new ArrayList<>();
+        TableConfig mainTable = new TableConfig();
+        mainTable.setTableName("xjr_oa_news");
+        mainTable.setIsMain(true);
+        mainTable.setPkField(GlobalConstant.DEFAULT_PK);
+        mainTable.setPkType(GlobalConstant.DEFAULT_PK_TYPE);
+
+        TableConfig childTable1 = new TableConfig();
+        childTable1.setTableName("xjr_oa_news_relation");
+        childTable1.setIsMain(false);
+        childTable1.setPkField(GlobalConstant.DEFAULT_PK);
+        childTable1.setPkType(GlobalConstant.DEFAULT_PK_TYPE);
+        childTable1.setRelationField("news_id");
+        childTable1.setRelationTableField(GlobalConstant.DEFAULT_PK);
+
+
+        TableConfig childTable2 = new TableConfig();
+        childTable2.setTableName("xjr_oa_news_relation_config");
+        childTable2.setIsMain(false);
+        childTable2.setPkField(GlobalConstant.DEFAULT_PK);
+        childTable2.setPkType(GlobalConstant.DEFAULT_PK_TYPE);
+        childTable2.setRelationField("news_id");
+        childTable2.setRelationTableField(GlobalConstant.DEFAULT_PK);
+
+        tableConfigs.add(mainTable);
+        tableConfigs.add(childTable1);
+        tableConfigs.add(childTable2);
+
+        ApiGenerateCodesDto params = new ApiGenerateCodesDto();
+        params.setAuthor("fanxp");
+        params.setPackageName("test");
+        params.setTableConfigs(tableConfigs);
+
+        apiGeneratorService.generateCodes(params);
+    }
+
+    @Test
+    public void freeMarkerTest() throws IOException, TemplateException {
+
+        List<TableConfig> tableConfigs = new ArrayList<>();
+        TableConfig mainTable = new TableConfig();
+        mainTable.setTableName("xjr_oa_news");
+        mainTable.setIsMain(true);
+        mainTable.setPkField(GlobalConstant.DEFAULT_PK);
+        mainTable.setPkType(GlobalConstant.DEFAULT_PK_TYPE);
+
+        TableConfig childTable1 = new TableConfig();
+        childTable1.setTableName("xjr_oa_news_relation");
+        childTable1.setIsMain(false);
+        childTable1.setPkField(GlobalConstant.DEFAULT_PK);
+        childTable1.setPkType(GlobalConstant.DEFAULT_PK_TYPE);
+        childTable1.setRelationField("news_id");
+        childTable1.setRelationTableField(GlobalConstant.DEFAULT_PK);
+
+
+        TableConfig childTable2 = new TableConfig();
+        childTable2.setTableName("xjr_oa_news_relation_config");
+        childTable2.setIsMain(false);
+        childTable2.setPkField(GlobalConstant.DEFAULT_PK);
+        childTable2.setPkType(GlobalConstant.DEFAULT_PK_TYPE);
+        childTable2.setRelationField("news_id");
+        childTable2.setRelationTableField(GlobalConstant.DEFAULT_PK);
+
+        tableConfigs.add(mainTable);
+        tableConfigs.add(childTable1);
+        tableConfigs.add(childTable2);
+
+        GeneratorConfig generatorConfig = new GeneratorConfig();
+        generatorConfig.setTableConfigs(tableConfigs);
+
+
+
+        List<Table> tableInfos = new ArrayList<>();
+        for (TableConfig tableConfig : generatorConfig.getTableConfigs()) {
+            //判断是否为默认数据源
+            if (StrUtil.equalsIgnoreCase(generatorConfig.getDatabaseId(), GlobalConstant.DEFAULT_DATASOURCE_KEY)) {
+                tableInfos.add(MetaUtil.getTableMeta(DatasourceUtil.getDatasourceMaster(), tableConfig.getTableName()));
+            } else {
+                tableInfos.add(MetaUtil.getTableMeta(DatasourceUtil.getDataSource(generatorConfig.getDatabaseId()), tableConfig.getTableName()));
+            }
+        }
+
+        System.out.println(tableInfos);
+
+        Map<String, String> entityCodeMap = new HashMap<>(tableInfos.size());
+        // 遍历数据表配置 根据表明搜索表信息  然后生成代码
+        for (Table tableInfo : tableInfos) {
+            //获取表的所有字段
+            Collection<Column> columns = tableInfo.getColumns();
+            List<FieldConfig> fieldConfigList = new ArrayList<>();
+
+            for (Column column : columns) {
+                FieldConfig fieldConfig = new FieldConfig();
+
+                if (GlobalConstant.AUTO_INSERT.contains(column.getName())) {
+                    fieldConfig.setAutoInsert(true);
+                }
+
+                if (GlobalConstant.AUTO_UPDATE.contains(column.getName())) {
+                    fieldConfig.setAutoUpdate(true);
+                }
+
+                if (StrUtil.equalsIgnoreCase(column.getName(), GlobalConstant.DELETE_MARK)) {
+                    fieldConfig.setDeleteMark(true);
+                }
+                fieldConfig.setFieldComment(column.getComment());
+                fieldConfig.setPk(column.isPk());
+                fieldConfig.setFieldType(JdbcToJavaUtil.getClassName(column.getTypeEnum()));
+                fieldConfig.setFieldName(StrUtil.toCamelCase(column.getName()));
+
+                fieldConfigList.add(fieldConfig);
+
+            }
+
+
+            //如果有子表  每多一个子表  多加1个长度
+            Map<String, Object> entityMap = new HashMap<>(8);
+            entityMap.put(EntityConstant.PACKAGE, GlobalConstant.GENERATOR_DEFAULT_PATH + StringPool.DOT + "test" + StringPool.DOT + "entity");
+            entityMap.put(EntityConstant.AUTH_NAME, "fanxp");
+            entityMap.put(EntityConstant.DATE, LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
+            entityMap.put(EntityConstant.TABLE_NAME, tableInfo.getTableName());
+            entityMap.put(EntityConstant.TABLE_COMMENT, tableInfo.getComment());
+            //先将表明转换为驼峰命名 然后在转换为首字母大写
+            entityMap.put(EntityConstant.ENTITY_CLASS_NAME, StrUtil.upperFirst(StrUtil.toCamelCase(tableInfo.getTableName())));
+            entityMap.put(EntityConstant.TABLE_FIELDS, fieldConfigList);
+
+            //如果是多表关联 则需要添加关联表的信息  判断数据表配置是否大于1  并且  是主表
+            boolean isMainTable = generatorConfig.getTableConfigs().stream().anyMatch(x -> StrUtil.equals(x.getTableName(), tableInfo.getTableName()) && x.getIsMain());
+            if (tableInfos.size() > 1 && isMainTable) {
+                List<TableConfig> childTables = generatorConfig.getTableConfigs().stream()
+                        .filter(x -> !x.getIsMain())
+                        .collect(Collectors.toList());
+
+                List<TableConfig> newChildTables = new ArrayList<>();
+                for (TableConfig childTable : childTables) {
+                    TableConfig newTableConfig = BeanUtil.toBean(childTable, TableConfig.class);
+
+                    newTableConfig.setRelationField(StrUtil.toCamelCase(childTable.getRelationField()));
+                    newTableConfig.setRelationTableField(StrUtil.toCamelCase(childTable.getRelationTableField()));
+                    newTableConfig.setTableName(StrUtil.toCamelCase(childTable.getTableName()));
+
+                    newChildTables.add(newTableConfig);
+                }
+//                Optional<TableConfig> parentTable = generatorConfig.getTableConfigs().stream().filter(TableConfig::getIsMain).findFirst();
+                entityMap.put(EntityConstant.CHILD_TABLES, newChildTables);
+//                parentTable.ifPresent(x -> entityMap.put(EntityConstant.PARENT_RELATION_FIELD_KEY, x.getRelationTableField()));
+            }
+
+
+            //生产目标代码
+//            Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
+//            configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
+//            configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
+//            Template template = configuration.getTemplate(ENTITY_TEMPLATE_NAME);
+
+            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(ENTITY_TEMPLATE_NAME);
+            String entityContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, entityMap);
+
+            entityCodeMap.put(StrUtil.upperFirst(StrUtil.toCamelCase(tableInfo.getTableName())), entityContent);
+        }
+
+        System.out.println(entityCodeMap);
+
+    }
+}