feat(代码生成): 支持anyline 动态获取表元数据

- 1. 支持代码生成模板 从 github获取
- 2. 重构代码生成的默认值从配置类获取
This commit is contained in:
冷冷 2024-07-15 23:16:29 +08:00
parent c8d4eeb1c5
commit 921732ab68
38 changed files with 1504 additions and 1152 deletions

File diff suppressed because one or more lines are too long

View File

@ -1,20 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -30,12 +14,13 @@
<description>代码生成模块</description> <description>代码生成模块</description>
<properties>
<screw.version>0.0.6</screw.version>
<anyline.version>8.7.2-jdk17-20240530</anyline.version>
<configuration.version>1.10</configuration.version>
</properties>
<dependencies> <dependencies>
<!--接口文档-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-swagger</artifactId>
</dependency>
<!--注册中心客户端--> <!--注册中心客户端-->
<dependency> <dependency>
<groupId>com.alibaba.cloud</groupId> <groupId>com.alibaba.cloud</groupId>
@ -46,16 +31,17 @@
<groupId>com.alibaba.cloud</groupId> <groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency> </dependency>
<!--断路器依赖--> <!--数据操作-->
<dependency> <dependency>
<groupId>com.pig4cloud</groupId> <groupId>com.pig4cloud</groupId>
<artifactId>pig-common-feign</artifactId> <artifactId>pig-common-mybatis</artifactId>
</dependency> </dependency>
<!--数据源--> <!--动态数据源 数据操作-->
<dependency> <dependency>
<groupId>com.pig4cloud</groupId> <groupId>com.pig4cloud</groupId>
<artifactId>pig-common-datasource</artifactId> <artifactId>pig-common-datasource</artifactId>
</dependency> </dependency>
<!--mybatis-->
<dependency> <dependency>
<groupId>com.baomidou</groupId> <groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId> <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
@ -64,30 +50,49 @@
<groupId>com.mysql</groupId> <groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId> <artifactId>mysql-connector-j</artifactId>
</dependency> </dependency>
<!--common--> <!--anyline-->
<dependency> <dependency>
<groupId>cn.hutool</groupId> <groupId>org.anyline</groupId>
<artifactId>hutool-json</artifactId> <artifactId>anyline-environment-spring-data-jdbc</artifactId>
<version>${anyline.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.anyline</groupId>
<artifactId>anyline-data-jdbc-mysql</artifactId>
<version>${anyline.version}</version>
</dependency>
<!--common-->
<dependency> <dependency>
<groupId>com.pig4cloud</groupId> <groupId>com.pig4cloud</groupId>
<artifactId>pig-common-core</artifactId> <artifactId>pig-common-core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
</dependency>
<dependency> <dependency>
<groupId>commons-configuration</groupId> <groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId> <artifactId>commons-configuration</artifactId>
<version>${configuration.version}</version> <version>${configuration.version}</version>
</dependency> </dependency>
<!--日志处理--> <!--swagger-->
<dependency> <dependency>
<groupId>com.pig4cloud</groupId> <groupId>com.pig4cloud</groupId>
<artifactId>pig-common-log</artifactId> <artifactId>pig-common-swagger</artifactId>
</dependency> </dependency>
<!--安全模块--> <!--安全模块-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-xss</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.pig4cloud</groupId> <groupId>com.pig4cloud</groupId>
<artifactId>pig-common-security</artifactId> <artifactId>pig-common-security</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-log</artifactId>
</dependency>
<!--代码生成模板引擎--> <!--代码生成模板引擎-->
<dependency> <dependency>
<groupId>org.apache.velocity</groupId> <groupId>org.apache.velocity</groupId>
@ -101,10 +106,15 @@
</dependency> </dependency>
<!--生成文档--> <!--生成文档-->
<dependency> <dependency>
<groupId>io.springboot.plugin</groupId> <groupId>group.springframework.plugin</groupId>
<artifactId>screw-spring-boot-starter</artifactId> <artifactId>screw-spring-boot-starter</artifactId>
<version>${screw.version}</version> <version>${screw.version}</version>
</dependency> </dependency>
<!--web 模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--undertow容器--> <!--undertow容器-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@ -113,13 +123,9 @@
</dependencies> </dependencies>
<profiles> <profiles>
<profile>
<id>boot</id>
</profile>
<profile> <profile>
<id>cloud</id> <id>cloud</id>
<activation> <activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault> <activeByDefault>true</activeByDefault>
</activation> </activation>
<build> <build>
@ -127,13 +133,29 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<loaderImplementation>CLASSIC</loaderImplementation>
</configuration>
</execution>
</executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>io.fabric8</groupId> <groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId> <artifactId>docker-maven-plugin</artifactId>
<configuration>
<skip>false</skip>
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile>
<id>boot</id>
</profile>
</profiles> </profiles>
</project> </project>

View File

@ -20,6 +20,7 @@ package com.pig4cloud.pig.codegen;
import com.pig4cloud.pig.common.datasource.annotation.EnableDynamicDataSource; import com.pig4cloud.pig.common.datasource.annotation.EnableDynamicDataSource;
import com.pig4cloud.pig.common.feign.annotation.EnablePigFeignClients; import com.pig4cloud.pig.common.feign.annotation.EnablePigFeignClients;
import com.pig4cloud.pig.common.security.annotation.EnablePigResourceServer; import com.pig4cloud.pig.common.security.annotation.EnablePigResourceServer;
import com.pig4cloud.pig.common.swagger.annotation.EnablePigDoc;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@ -30,6 +31,7 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
*/ */
@EnableDynamicDataSource @EnableDynamicDataSource
@EnablePigFeignClients @EnablePigFeignClients
@EnablePigDoc("gen")
@EnableDiscoveryClient @EnableDiscoveryClient
@EnablePigResourceServer @EnablePigResourceServer
@SpringBootApplication @SpringBootApplication

View File

@ -0,0 +1,75 @@
package com.pig4cloud.pig.codegen.config;
import cn.smallbun.screw.core.constant.DefaultConstants;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 代码生成默认配置类
*
* @author lengleng
* @date 2024/7/15
*/
@Data
@Configuration(proxyBeanMethods = false)
@ConfigurationProperties(prefix = PigCodeGenDefaultProperties.PREFIX)
public class PigCodeGenDefaultProperties {
public static final String PREFIX = "codegen";
/**
* 是否开启在线更新
*/
private boolean autoCheckVersion = true;
/**
* 模板项目地址
*/
private String onlineUrl = DefaultConstants.CGTM_URL;
/**
* 生成代码的包名
*/
private String packageName = "com.pig4cloud.pig";
/**
* 生成代码的版本
*/
private String version = "1.0.0";
/**
* 生成代码的模块名
*/
private String moduleName = "admin";
/**
* 生成代码的后端路径
*/
private String backendPath = "pig";
/**
* 生成代码的前端路径
*/
private String frontendPath = "pig-ui";
/**
* 生成代码的作者
*/
private String author = "pig";
/**
* 生成代码的邮箱
*/
private String email = "sw@pigx.vip";
/**
* 表单布局一列两列
*/
private Integer formLayout = 2;
/**
* 下载方式 0 文件下载1写入目录
*/
private String generatorType = "0";
}

View File

@ -18,7 +18,6 @@ package com.pig4cloud.pig.codegen.controller;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.smallbun.screw.boot.config.Screw; import cn.smallbun.screw.boot.config.Screw;
import cn.smallbun.screw.boot.properties.ScrewProperties; import cn.smallbun.screw.boot.properties.ScrewProperties;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
@ -30,6 +29,7 @@ import com.pig4cloud.pig.codegen.service.GenDatasourceConfService;
import com.pig4cloud.pig.common.core.util.R; import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.core.util.SpringContextHolder; import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.security.annotation.Inner; import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.common.xss.core.XssCleanIgnore;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows; import lombok.SneakyThrows;
@ -93,6 +93,7 @@ public class GenDsConfController {
* @return R * @return R
*/ */
@PostMapping @PostMapping
@XssCleanIgnore
public R save(@RequestBody GenDatasourceConf datasourceConf) { public R save(@RequestBody GenDatasourceConf datasourceConf) {
return R.ok(datasourceConfService.saveDsByEnc(datasourceConf)); return R.ok(datasourceConfService.saveDsByEnc(datasourceConf));
} }
@ -103,6 +104,7 @@ public class GenDsConfController {
* @return R * @return R
*/ */
@PutMapping @PutMapping
@XssCleanIgnore
public R updateById(@RequestBody GenDatasourceConf conf) { public R updateById(@RequestBody GenDatasourceConf conf) {
return R.ok(datasourceConfService.updateDsByEnc(conf)); return R.ok(datasourceConfService.updateDsByEnc(conf));
} }
@ -133,11 +135,11 @@ public class GenDsConfController {
ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class); ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class);
// 生成 // 生成
byte[] data = screw.documentGeneration(dataSource, screwProperties).toByteArray(); byte[] data = screw.documentGeneration(dsName, dataSource, screwProperties).toByteArray();
response.reset(); response.reset();
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType(ContentType.OCTET_STREAM.getValue()); response.setContentType("application/octet-stream");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data); IoUtil.write(response.getOutputStream(), Boolean.FALSE, data);
} }
} }

View File

@ -23,7 +23,7 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity; import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.service.GenGroupService; import com.pig4cloud.pig.codegen.service.GenGroupService;
import com.pig4cloud.pig.codegen.util.vo.GroupVo; import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO; import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO;
import com.pig4cloud.pig.common.core.util.R; import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog; import com.pig4cloud.pig.common.log.annotation.SysLog;
@ -55,6 +55,7 @@ public class GenGroupController {
/** /**
* 分页查询 * 分页查询
*
* @param page 分页对象 * @param page 分页对象
* @param genGroup 模板分组 * @param genGroup 模板分组
* @return * @return
@ -71,6 +72,7 @@ public class GenGroupController {
/** /**
* 通过id查询模板分组 * 通过id查询模板分组
*
* @param id id * @param id id
* @return R * @return R
*/ */
@ -83,6 +85,7 @@ public class GenGroupController {
/** /**
* 新增模板分组 * 新增模板分组
*
* @param genTemplateGroup 模板分组 * @param genTemplateGroup 模板分组
* @return R * @return R
*/ */
@ -97,6 +100,7 @@ public class GenGroupController {
/** /**
* 修改模板分组 * 修改模板分组
*
* @param groupVo 模板分组 * @param groupVo 模板分组
* @return R * @return R
*/ */
@ -104,13 +108,14 @@ public class GenGroupController {
@SysLog("修改模板分组") @SysLog("修改模板分组")
@PutMapping @PutMapping
@HasPermission("codegen_group_edit") @HasPermission("codegen_group_edit")
public R updateById(@RequestBody GroupVo groupVo) { public R updateById(@RequestBody GroupVO groupVo) {
genGroupService.updateGroupAndTemplateById(groupVo); genGroupService.updateGroupAndTemplateById(groupVo);
return R.ok(); return R.ok();
} }
/** /**
* 通过id删除模板分组 * 通过id删除模板分组
*
* @param ids id列表 * @param ids id列表
* @return R * @return R
*/ */
@ -125,6 +130,7 @@ public class GenGroupController {
/** /**
* 导出excel 表格 * 导出excel 表格
*
* @param genGroup 查询条件 * @param genGroup 查询条件
* @return excel 文件流 * @return excel 文件流
*/ */
@ -135,10 +141,15 @@ public class GenGroupController {
return genGroupService.list(Wrappers.query(genGroup)); return genGroupService.list(Wrappers.query(genGroup));
} }
/**
* @return 响应信息主体
*/
@GetMapping("/list") @GetMapping("/list")
@Operation(summary = "查询列表", description = "查询列表") @Operation(summary = "查询列表", description = "查询列表")
public R list() { public R list() {
List<GenGroupEntity> list = genGroupService.list(); List<GenGroupEntity> list = genGroupService.list(Wrappers.<GenGroupEntity>lambdaQuery()
.orderByDesc(GenGroupEntity::getCreateTime));
return R.ok(list); return R.ok(list);
} }

View File

@ -61,31 +61,74 @@ public class GenTableController {
@Operation(summary = "分页查询", description = "分页查询") @Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page") @GetMapping("/page")
public R getTablePage(Page page, GenTable table) { public R getTablePage(Page page, GenTable table) {
return R.ok(tableService.queryTablePage(page, table));
return R.ok(tableService.list(page, table));
} }
/** /**
* 通过id查询列属性 * 通过id查询表信息代码生成设置 + + 字段设置
* @param id id * @param id id
* @return R * @return R
*/ */
@Operation(summary = "通过id查询", description = "通过id查询") @Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}") @GetMapping("/{id}")
public R getById(@PathVariable("id") Long id) { public R getTable(@PathVariable("id") Long id) {
return R.ok(tableService.getById(id)); return R.ok(tableService.getById(id));
} }
/** /**
* 新增列属性 * 查询数据源所有表
* @param table 列属性 * @param dsName 数据源
* @return R
*/ */
@Operation(summary = "新增列属性", description = "新增列属性") @GetMapping("/list/{dsName}")
@SysLog("新增列属性") public R listTable(@PathVariable("dsName") String dsName) {
@PostMapping return R.ok(tableService.queryTableList(dsName));
public R save(@RequestBody GenTable table) { }
return R.ok(tableService.save(table));
/**
* 获取表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/{dsName}/{tableName}")
public R<GenTable> getTable(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
}
/**
* 查询表DDL语句
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/column/{dsName}/{tableName}")
public R getColumn(@PathVariable("dsName") String dsName, @PathVariable String tableName) throws Exception {
return R.ok(tableService.queryTableColumn(dsName, tableName));
}
/**
* 查询表DDL语句
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/ddl/{dsName}/{tableName}")
public R getDdl(@PathVariable("dsName") String dsName, @PathVariable String tableName) throws Exception {
return R.ok(tableService.queryTableDdl(dsName, tableName));
}
/**
* 同步表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/sync/{dsName}/{tableName}")
public R<GenTable> syncTable(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
// 表配置删除
tableService.remove(
Wrappers.<GenTable>lambdaQuery().eq(GenTable::getDsName, dsName).eq(GenTable::getTableName, tableName));
// 字段配置删除
tableColumnService.remove(Wrappers.<GenTableColumnEntity>lambdaQuery()
.eq(GenTableColumnEntity::getDsName, dsName)
.eq(GenTableColumnEntity::getTableName, tableName));
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
} }
/** /**
@ -101,15 +144,16 @@ public class GenTableController {
} }
/** /**
* 通过id删除列属性 * 修改表字段数据
* @param id id * @param dsName 数据源
* @return R * @param tableName 表名称
* @param tableFieldList 字段列表
*/ */
@Operation(summary = "通过id删除列属性", description = "通过id删除列属性") @PutMapping("/field/{dsName}/{tableName}")
@SysLog("通过id删除列属性") public R<String> updateTableField(@PathVariable("dsName") String dsName, @PathVariable String tableName,
@DeleteMapping("/{id}") @RequestBody List<GenTableColumnEntity> tableFieldList) {
public R removeById(@PathVariable Long id) { tableColumnService.updateTableField(dsName, tableName, tableFieldList);
return R.ok(tableService.removeById(id)); return R.ok();
} }
/** /**
@ -123,54 +167,4 @@ public class GenTableController {
return tableService.list(Wrappers.query(table)); return tableService.list(Wrappers.query(table));
} }
@GetMapping("/list/{dsName}")
public R listTable(@PathVariable("dsName") String dsName) {
return R.ok(tableService.queryDsAllTable(dsName));
}
@GetMapping("/column/{dsName}/{tableName}")
public R column(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
return R.ok(tableService.queryColumn(dsName, tableName));
}
/**
* 获取表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/{dsName}/{tableName}")
public R<GenTable> info(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
}
/**
* 同步表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/sync/{dsName}/{tableName}")
public R<GenTable> sync(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
// 表配置删除
tableService.remove(
Wrappers.<GenTable>lambdaQuery().eq(GenTable::getDsName, dsName).eq(GenTable::getTableName, tableName));
// 字段配置删除
tableColumnService.remove(Wrappers.<GenTableColumnEntity>lambdaQuery()
.eq(GenTableColumnEntity::getDsName, dsName)
.eq(GenTableColumnEntity::getTableName, tableName));
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
}
/**
* 修改表字段数据
* @param dsName 数据源
* @param tableName 表名称
* @param tableFieldList 字段列表
*/
@PutMapping("/field/{dsName}/{tableName}")
public R<String> updateTableField(@PathVariable("dsName") String dsName, @PathVariable String tableName,
@RequestBody List<GenTableColumnEntity> tableFieldList) {
tableColumnService.updateTableField(dsName, tableName, tableFieldList);
return R.ok();
}
} }

View File

@ -27,6 +27,7 @@ import com.pig4cloud.pig.codegen.service.GenTemplateService;
import com.pig4cloud.pig.common.core.util.R; import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog; import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.HasPermission; import com.pig4cloud.pig.common.security.annotation.HasPermission;
import com.pig4cloud.pig.common.xss.core.XssCleanIgnore;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel; import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
@ -54,6 +55,7 @@ public class GenTemplateController {
/** /**
* 分页查询 * 分页查询
*
* @param page 分页对象 * @param page 分页对象
* @param genTemplate 模板 * @param genTemplate 模板
* @return * @return
@ -61,7 +63,7 @@ public class GenTemplateController {
@Operation(summary = "分页查询", description = "分页查询") @Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page") @GetMapping("/page")
@HasPermission("codegen_template_view") @HasPermission("codegen_template_view")
public R getgenTemplatePage(Page page, GenTemplateEntity genTemplate) { public R getGenTemplatePage(Page page, GenTemplateEntity genTemplate) {
LambdaQueryWrapper<GenTemplateEntity> wrapper = Wrappers.<GenTemplateEntity>lambdaQuery() LambdaQueryWrapper<GenTemplateEntity> wrapper = Wrappers.<GenTemplateEntity>lambdaQuery()
.like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId()) .like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId())
.like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName, .like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName,
@ -71,17 +73,20 @@ public class GenTemplateController {
/** /**
* 查询全部模板 * 查询全部模板
*
* @return * @return
*/ */
@Operation(summary = "查询全部", description = "查询全部") @Operation(summary = "查询全部", description = "查询全部")
@GetMapping("/list") @GetMapping("/list")
@HasPermission("codegen_template_view") @HasPermission("codegen_template_view")
public R list() { public R list() {
return R.ok(genTemplateService.list(Wrappers.emptyWrapper())); return R.ok(genTemplateService.list(Wrappers.<GenTemplateEntity>lambdaQuery()
.orderByDesc(GenTemplateEntity::getCreateTime)));
} }
/** /**
* 通过id查询模板 * 通过id查询模板
*
* @param id id * @param id id
* @return R * @return R
*/ */
@ -94,9 +99,11 @@ public class GenTemplateController {
/** /**
* 新增模板 * 新增模板
*
* @param genTemplate 模板 * @param genTemplate 模板
* @return R * @return R
*/ */
@XssCleanIgnore
@Operation(summary = "新增模板", description = "新增模板") @Operation(summary = "新增模板", description = "新增模板")
@SysLog("新增模板") @SysLog("新增模板")
@PostMapping @PostMapping
@ -107,9 +114,11 @@ public class GenTemplateController {
/** /**
* 修改模板 * 修改模板
*
* @param genTemplate 模板 * @param genTemplate 模板
* @return R * @return R
*/ */
@XssCleanIgnore
@Operation(summary = "修改模板", description = "修改模板") @Operation(summary = "修改模板", description = "修改模板")
@SysLog("修改模板") @SysLog("修改模板")
@PutMapping @PutMapping
@ -120,6 +129,7 @@ public class GenTemplateController {
/** /**
* 通过id删除模板 * 通过id删除模板
*
* @param ids id列表 * @param ids id列表
* @return R * @return R
*/ */
@ -133,6 +143,7 @@ public class GenTemplateController {
/** /**
* 导出excel 表格 * 导出excel 表格
*
* @param genTemplate 查询条件 * @param genTemplate 查询条件
* @return excel 文件流 * @return excel 文件流
*/ */
@ -143,4 +154,29 @@ public class GenTemplateController {
return genTemplateService.list(Wrappers.query(genTemplate)); return genTemplateService.list(Wrappers.query(genTemplate));
} }
/**
* 在线更新模板
*
* @return R
*/
@Operation(summary = "在线更新模板", description = "在线更新模板")
@GetMapping("/online")
@HasPermission("codegen_template_view")
public R online() {
return genTemplateService.onlineUpdate();
}
/**
* 检查版本
*
* @return {@link R }
*/
@Operation(summary = "在线检查模板", description = "在线检查模板")
@GetMapping("/checkVersion")
@HasPermission("codegen_template_view")
public R checkVersion() {
return genTemplateService.checkVersion();
}
} }

View File

@ -50,6 +50,7 @@ public class GeneratorController {
/** /**
* ZIP 下载生成代码 * ZIP 下载生成代码
*
* @param tableIds 数据表ID * @param tableIds 数据表ID
* @param response 流输出对象 * @param response 流输出对象
*/ */
@ -92,6 +93,7 @@ public class GeneratorController {
/** /**
* 预览代码 * 预览代码
*
* @param tableId 表ID * @param tableId 表ID
* @return * @return
*/ */

View File

@ -157,12 +157,33 @@ public class GenTable extends Model<GenTable> {
*/ */
private Long style; private Long style;
/**
* 子表名称
*/
private String childTableName;
/**
* 主表关联键
*/
private String mainField;
/**
* 子表关联键
*/
private String childField;
/** /**
* 字段列表 * 字段列表
*/ */
@TableField(exist = false) @TableField(exist = false)
private List<GenTableColumnEntity> fieldList; private List<GenTableColumnEntity> fieldList;
/**
* 子表字段列表
*/
@TableField(exist = false)
private List<GenTableColumnEntity> childFieldList;
/** /**
* 代码风格模版分组信息 * 代码风格模版分组信息
*/ */

View File

@ -19,7 +19,7 @@ package com.pig4cloud.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity; import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.util.vo.GroupVo; import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
@ -32,6 +32,6 @@ import org.apache.ibatis.annotations.Param;
@Mapper @Mapper
public interface GenGroupMapper extends BaseMapper<GenGroupEntity> { public interface GenGroupMapper extends BaseMapper<GenGroupEntity> {
GroupVo getGroupVoById(@Param("id") Long id); GroupVO getGroupVoById(@Param("id") Long id);
} }

View File

@ -1,97 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pig.codegen.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.codegen.entity.ColumnEntity;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 代码生成器
*
* @author lengleng
* @date 2018-07-30
*/
public interface GeneratorMapper extends BaseMapper<ColumnEntity> {
/**
* 查询全部的表
* @return
*/
@InterceptorIgnore(tenantLine = "true")
List<Map<String, Object>> queryTable();
/**
* 分页查询表格
* @param page 分页信息
* @param tableName 表名称
* @return
*/
@InterceptorIgnore(tenantLine = "true")
IPage<Map<String, Object>> queryTable(Page page, @Param("tableName") String tableName);
/**
* 查询表信息
* @param tableName 表名称
* @param dsName 数据源名称
* @return
*/
@DS("#last")
@InterceptorIgnore(tenantLine = "true")
Map<String, String> queryTable(@Param("tableName") String tableName, String dsName);
/**
* 分页查询表分页信息
* @param page
* @param tableName
* @param dsName
* @return
*/
@DS("#last")
@InterceptorIgnore(tenantLine = "true")
IPage<ColumnEntity> selectTableColumn(Page page, @Param("tableName") String tableName,
@Param("dsName") String dsName);
/**
* 查询表全部列信息
* @param tableName
* @param dsName
* @return
*/
@DS("#last")
@InterceptorIgnore(tenantLine = "true")
List<ColumnEntity> selectTableColumn(@Param("tableName") String tableName, @Param("dsName") String dsName);
/**
* 查询表全部列信息
* @param tableName 表名称
* @param dsName 数据源名称
* @return
*/
@DS("#last")
@InterceptorIgnore(tenantLine = "true")
List<Map<String, String>> selectMapTableColumn(@Param("tableName") String tableName, String dsName);
}

View File

@ -1,31 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pig.codegen.mapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 支持 mysql 代码生成器
*
* @author lengleng
* @date 2020-12-11
*/
@Mapper
public interface GeneratorMysqlMapper extends GeneratorMapper {
}

View File

@ -19,7 +19,7 @@ package com.pig4cloud.pig.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity; import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.util.vo.GroupVo; import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO; import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO;
/** /**
@ -33,7 +33,7 @@ public interface GenGroupService extends IService<GenGroupEntity> {
void saveGenGroup(TemplateGroupDTO genTemplateGroup); void saveGenGroup(TemplateGroupDTO genTemplateGroup);
/** /**
* 删除分组关系 * 删除分组极其关系
* @param ids * @param ids
*/ */
void delGroupAndTemplate(Long[] ids); void delGroupAndTemplate(Long[] ids);
@ -42,12 +42,12 @@ public interface GenGroupService extends IService<GenGroupEntity> {
* 查询group数据 * 查询group数据
* @param id * @param id
*/ */
GroupVo getGroupVoById(Long id); GroupVO getGroupVoById(Long id);
/** /**
* 更新group数据 * 更新group数据
* @param groupVo * @param GroupVo
*/ */
void updateGroupAndTemplateById(GroupVo groupVo); void updateGroupAndTemplateById(GroupVO GroupVo);
} }

View File

@ -30,18 +30,8 @@ import java.util.List;
*/ */
public interface GenTableColumnService extends IService<GenTableColumnEntity> { public interface GenTableColumnService extends IService<GenTableColumnEntity> {
/**
* 初始化字段列表
* @param tableFieldList 表字段列表
*/
void initFieldList(List<GenTableColumnEntity> tableFieldList); void initFieldList(List<GenTableColumnEntity> tableFieldList);
/**
* 更新表字段
* @param dsName 数据源名称
* @param tableName 表名称
* @param tableFieldList 表字段列表
*/
void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList); void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList);
} }

View File

@ -21,9 +21,9 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenTable; import com.pig4cloud.pig.codegen.entity.GenTable;
import org.anyline.metadata.Table;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* 列属性 * 列属性
@ -33,41 +33,50 @@ import java.util.Map;
*/ */
public interface GenTableService extends IService<GenTable> { public interface GenTableService extends IService<GenTable> {
/**
* 获取默认配置信息
* @return 默认配置信息
*/
Map<String, Object> getGeneratorConfig();
/** /**
* 分页查询表格列表 * 查询对应数据源的表
* @param page 分页对象 *
* @param page 分页信息
* @param table 查询条件 * @param table 查询条件
* @return 格列表分页结果 * @return
*/ */
IPage list(Page<GenTable> page, GenTable table); IPage queryTablePage(Page<Table> page, GenTable table);
/** /**
* 根据数据源名称和表名查询或构建表格 * 查询表信息然后插入到中间表中
* @param dsName 数据源名称 *
* @param dsName 数据源
* @param tableName 表名 * @param tableName 表名
* @return 查询到的表格信息 * @return GenTable
*/ */
GenTable queryOrBuildTable(String dsName, String tableName); GenTable queryOrBuildTable(String dsName, String tableName);
/** /**
* 查询指定数据源下的所有表格 * 查询表ddl 语句
*
* @param dsName 数据源名称 * @param dsName 数据源名称
* @return 所有表格的列表 * @param tableName 表名称
* @return ddl 语句
* @throws Exception
*/ */
List<Map<String, Object>> queryDsAllTable(String dsName); String queryTableDdl(String dsName, String tableName) throws Exception;
/** /**
* 查询指定数据源和表名的列信息 * 查询数据源里面的全部表
*
* @param dsName 数据源名称 * @param dsName 数据源名称
* @param tableName 表名 * @return table
* @return 列信息列表
*/ */
List<Map<String, String>> queryColumn(String dsName, String tableName); List<String> queryTableList(String dsName);
/**
* 查询表的全部字段
*
* @param dsName 数据源
* @param tableName 表名称
* @return column
*/
List<String> queryTableColumn(String dsName, String tableName);
} }

View File

@ -19,6 +19,7 @@ package com.pig4cloud.pig.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pig.codegen.entity.GenTemplateEntity; import com.pig4cloud.pig.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pig.common.core.util.R;
/** /**
* 模板 * 模板
@ -28,4 +29,18 @@ import com.pig4cloud.pig.codegen.entity.GenTemplateEntity;
*/ */
public interface GenTemplateService extends IService<GenTemplateEntity> { public interface GenTemplateService extends IService<GenTemplateEntity> {
/**
* 检查版本
*
* @return {@link R }
*/
R checkVersion();
/**
* 在线更新
*
* @return {@link R }
*/
R onlineUpdate();
} }

View File

@ -19,9 +19,8 @@ package com.pig4cloud.pig.codegen.service.impl;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty; import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.creator.druid.DruidConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.entity.GenDatasourceConf; import com.pig4cloud.pig.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pig.codegen.mapper.GenDatasourceConfMapper; import com.pig4cloud.pig.codegen.mapper.GenDatasourceConfMapper;
@ -53,10 +52,11 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
private final StringEncryptor stringEncryptor; private final StringEncryptor stringEncryptor;
private final DefaultDataSourceCreator druidDataSourceCreator; private final DataSourceCreator hikariDataSourceCreator;
/** /**
* 保存数据源并且加密 * 保存数据源并且加密
*
* @param conf * @param conf
* @return * @return
*/ */
@ -78,6 +78,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
/** /**
* 更新数据源 * 更新数据源
*
* @param conf 数据源信息 * @param conf 数据源信息
* @return * @return
*/ */
@ -103,6 +104,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
/** /**
* 通过数据源名称删除 * 通过数据源名称删除
*
* @param dsIds 数据源ID * @param dsIds 数据源ID
* @return * @return
*/ */
@ -117,6 +119,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
/** /**
* 添加动态数据源 * 添加动态数据源
*
* @param conf 数据源信息 * @param conf 数据源信息
*/ */
@Override @Override
@ -126,11 +129,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
dataSourceProperty.setUrl(conf.getUrl()); dataSourceProperty.setUrl(conf.getUrl());
dataSourceProperty.setUsername(conf.getUsername()); dataSourceProperty.setUsername(conf.getUsername());
dataSourceProperty.setPassword(conf.getPassword()); dataSourceProperty.setPassword(conf.getPassword());
DataSource dataSource = hikariDataSourceCreator.createDataSource(dataSourceProperty);
// 增加 ValidationQuery 参数
DruidConfig druidConfig = new DruidConfig();
dataSourceProperty.setDruid(druidConfig);
DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource); dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
@ -138,6 +137,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
/** /**
* 校验数据源配置是否有效 * 校验数据源配置是否有效
*
* @param conf 数据源信息 * @param conf 数据源信息
* @return 有效/无效 * @return 有效/无效
*/ */
@ -147,13 +147,11 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
// JDBC 配置形式 // JDBC 配置形式
if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) { if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) {
url = conf.getUrl(); url = conf.getUrl();
} } else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
// 主机形式 sql server 特殊处理 // 主机形式 sql server 特殊处理
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
} } else {
else {
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
} }
@ -161,8 +159,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
conf.setUrl(url); conf.setUrl(url);
try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) { try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) {
} } catch (SQLException e) {
catch (SQLException e) {
log.error("数据源配置 {} , 获取链接失败", conf.getName(), e); log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
throw new RuntimeException("数据库配置错误,链接失败"); throw new RuntimeException("数据库配置错误,链接失败");
} }

View File

@ -25,7 +25,7 @@ import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity;
import com.pig4cloud.pig.codegen.mapper.GenGroupMapper; import com.pig4cloud.pig.codegen.mapper.GenGroupMapper;
import com.pig4cloud.pig.codegen.service.GenGroupService; import com.pig4cloud.pig.codegen.service.GenGroupService;
import com.pig4cloud.pig.codegen.service.GenTemplateGroupService; import com.pig4cloud.pig.codegen.service.GenTemplateGroupService;
import com.pig4cloud.pig.codegen.util.vo.GroupVo; import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO; import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -87,7 +87,7 @@ public class GenGroupServiceImpl extends ServiceImpl<GenGroupMapper, GenGroupEnt
* @return * @return
*/ */
@Override @Override
public GroupVo getGroupVoById(Long id) { public GroupVO getGroupVoById(Long id) {
return baseMapper.getGroupVoById(id); return baseMapper.getGroupVoById(id);
} }
@ -96,7 +96,7 @@ public class GenGroupServiceImpl extends ServiceImpl<GenGroupMapper, GenGroupEnt
* @param groupVo * @param groupVo
*/ */
@Override @Override
public void updateGroupAndTemplateById(GroupVo groupVo) { public void updateGroupAndTemplateById(GroupVO groupVo) {
// 1.更新自身 // 1.更新自身
GenGroupEntity groupEntity = new GenGroupEntity(); GenGroupEntity groupEntity = new GenGroupEntity();
BeanUtil.copyProperties(groupVo, groupEntity); BeanUtil.copyProperties(groupVo, groupEntity);

View File

@ -78,6 +78,7 @@ public class GenTableColumnServiceImpl extends ServiceImpl<GenTableColumnMapper,
* @param tableFieldList 表单字段列表 * @param tableFieldList 表单字段列表
*/ */
@Override @Override
public void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList) { public void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList) {
AtomicInteger sort = new AtomicInteger(); AtomicInteger sort = new AtomicInteger();
this.updateBatchById(tableFieldList.stream() this.updateBatchById(tableFieldList.stream()

View File

@ -16,39 +16,41 @@
*/ */
package com.pig4cloud.pig.codegen.service.impl; package com.pig4cloud.pig.codegen.service.impl;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.NamingCase; import cn.hutool.core.text.NamingCase;
import cn.hutool.core.util.EnumUtil; import cn.hutool.core.util.EnumUtil;
import cn.hutool.json.JSONObject; import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder; import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.config.PigCodeGenDefaultProperties;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity; import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.entity.GenTable; import com.pig4cloud.pig.codegen.entity.GenTable;
import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity; import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pig.codegen.mapper.GenTableMapper; import com.pig4cloud.pig.codegen.mapper.GenTableMapper;
import com.pig4cloud.pig.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pig.codegen.service.GenGroupService; import com.pig4cloud.pig.codegen.service.GenGroupService;
import com.pig4cloud.pig.codegen.service.GenTableColumnService; import com.pig4cloud.pig.codegen.service.GenTableColumnService;
import com.pig4cloud.pig.codegen.service.GenTableService; import com.pig4cloud.pig.codegen.service.GenTableService;
import com.pig4cloud.pig.codegen.util.AutoFillEnum;
import com.pig4cloud.pig.codegen.util.BoolFillEnum; import com.pig4cloud.pig.codegen.util.BoolFillEnum;
import com.pig4cloud.pig.codegen.util.CommonColumnFiledEnum; import com.pig4cloud.pig.codegen.util.CommonColumnFiledEnum;
import com.pig4cloud.pig.codegen.util.GenKit; import com.pig4cloud.pig.codegen.util.GenKit;
import com.pig4cloud.pig.codegen.util.GeneratorTypeEnum;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.anyline.metadata.Column;
import org.anyline.metadata.Database;
import org.anyline.metadata.Table;
import org.anyline.proxy.ServiceProxy;
import org.anyline.service.AnylineService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
/** /**
@ -61,53 +63,88 @@ import java.util.Objects;
@RequiredArgsConstructor @RequiredArgsConstructor
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService { public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService {
/** private final PigCodeGenDefaultProperties configurationProperties;
* 默认配置信息
*/
private static final String CONFIG_PATH = "template/config.json";
private final GenTableColumnService columnService; private final GenTableColumnService columnService;
private final GenGroupService genGroupService; private final GenGroupService genGroupService;
/** /**
* 获取配置信息 * 查询表ddl 语句
* @return *
* @param dsName 数据源名称
* @param tableName 表名称
* @return ddl 语句
* @throws Exception
*/ */
@Override @Override
public Map<String, Object> getGeneratorConfig() { public String queryTableDdl(String dsName, String tableName) throws Exception {
ClassPathResource classPathResource = new ClassPathResource(CONFIG_PATH);
JSONObject jsonObject = JSONUtil.parseObj(IoUtil.readUtf8(classPathResource.getStream()));
return jsonObject.getRaw();
}
@Override
public List<Map<String, Object>> queryDsAllTable(String dsName) {
GeneratorMapper mapper = GenKit.getMapper(dsName);
// 手动切换数据源 // 手动切换数据源
DynamicDataSourceContextHolder.push(dsName); DynamicDataSourceContextHolder.push(dsName);
return mapper.queryTable(); Table table = ServiceProxy.metadata().table(tableName); // 获取表结构
} table.execute(false);// 不执行SQL
ServiceProxy.ddl().create(table);
@Override return table.getDdl();// 返回创建表的DDL
public List<Map<String, String>> queryColumn(String dsName, String tableName) {
GeneratorMapper mapper = GenKit.getMapper(dsName);
return mapper.selectMapTableColumn(tableName, dsName);
}
@Override
public IPage list(Page<GenTable> page, GenTable table) {
GeneratorMapper mapper = GenKit.getMapper(table.getDsName());
// 手动切换数据源
DynamicDataSourceContextHolder.push(table.getDsName());
return mapper.queryTable(page, table.getTableName());
} }
/** /**
* 获取表信息 * 查询表的全部字段
* @param dsName *
* @param tableName * @param dsName 数据源
* @return * @param tableName 表名称
* @return column
*/
@Override
public List<String> queryTableColumn(String dsName, String tableName) {
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
return ServiceProxy.metadata().columns(tableName).values().stream().map(Column::getName).toList();
}
/**
* 查询对应数据源的表
*
* @param page 分页信息
* @param table 查询条件
* @return
*/
@Override
public IPage queryTablePage(Page<Table> page, GenTable table) {
// 手动切换数据源
DynamicDataSourceContextHolder.push(table.getDsName());
List<Table> tableList = ServiceProxy.metadata().tables().values().stream().filter(t -> {
if (StrUtil.isBlank(table.getTableName())) {
return true;
}
return StrUtil.containsIgnoreCase(t.getName(false), table.getTableName());
}).toList();
// 根据 page 进行分页
List<Table> records = CollUtil.page((int) page.getCurrent() - 1, (int) page.getSize(), tableList);
page.setTotal(tableList.size());
page.setRecords(records);
return page;
}
/**
* 查询数据源里面的全部表
*
* @param dsName 数据源名称
* @return table
*/
@Override
public List<String> queryTableList(String dsName) {
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
return ServiceProxy.metadata().tables().values().stream().map(Table::getName).toList();
}
/**
* 查询表信息然后插入到中间表中
*
* @param dsName 数据源
* @param tableName 表名
* @return GenTable
*/ */
@Override @Override
public GenTable queryOrBuildTable(String dsName, String tableName) { public GenTable queryOrBuildTable(String dsName, String tableName) {
@ -131,76 +168,89 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
} }
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public GenTable tableImport(String dsName, String tableName) { protected GenTable tableImport(String dsName, String tableName) {
GeneratorMapper mapper = GenKit.getMapper(dsName);
// 手动切换数据源 // 手动切换数据源
DynamicDataSourceContextHolder.push(dsName); DynamicDataSourceContextHolder.push(dsName);
// 查询表是否存在 // 查询表是否存在
GenTable table = new GenTable(); GenTable table = new GenTable();
// 从数据库获取表信息 // 从数据库获取表信息
Map<String, String> queryTable = mapper.queryTable(tableName, dsName); AnylineService service = ServiceProxy.service();
Table tableMetadata = service.metadata().table(tableName);
Database database = service.metadata().database();
// 获取默认表配置信息 // 获取默认表配置信息
Map<String, Object> generatorConfig = getGeneratorConfig();
JSONObject project = (JSONObject) generatorConfig.get("project");
JSONObject developer = (JSONObject) generatorConfig.get("developer");
table.setPackageName(project.getStr("packageName")); table.setPackageName(configurationProperties.getPackageName());
table.setVersion(project.getStr("version")); table.setVersion(configurationProperties.getVersion());
table.setBackendPath(project.getStr("backendPath")); table.setBackendPath(configurationProperties.getBackendPath());
table.setFrontendPath(project.getStr("frontendPath")); table.setFrontendPath(configurationProperties.getFrontendPath());
table.setAuthor(developer.getStr("author")); table.setAuthor(configurationProperties.getAuthor());
table.setEmail(developer.getStr("email")); table.setEmail(configurationProperties.getEmail());
table.setTableName(tableName); table.setTableName(tableName);
table.setDsName(dsName); table.setDsName(dsName);
table.setTableComment(MapUtil.getStr(queryTable, "tableComment")); table.setTableComment(tableMetadata.getComment());
table.setDbType(MapUtil.getStr(queryTable, "dbType"));
table.setFormLayout(2); table.setDbType(database.getDatabase().title());
table.setGeneratorType(GeneratorTypeEnum.ZIP_DOWNLOAD.getValue()); table.setFormLayout(configurationProperties.getFormLayout());
table.setGeneratorType(configurationProperties.getGeneratorType());
table.setClassName(NamingCase.toPascalCase(tableName)); table.setClassName(NamingCase.toPascalCase(tableName));
table.setModuleName(GenKit.getModuleName(table.getPackageName())); // 模块名称默认为 admin
table.setModuleName(configurationProperties.getModuleName());
table.setFunctionName(GenKit.getFunctionName(tableName)); table.setFunctionName(GenKit.getFunctionName(tableName));
table.setCreateTime(LocalDateTime.now()); table.setCreateTime(LocalDateTime.now());
// 使用默认数据源
DynamicDataSourceContextHolder.clear();
this.save(table); this.save(table);
// 获取原生字段数据 // 获取原生字段数据
List<Map<String, String>> queryColumnList = mapper.selectMapTableColumn(tableName, dsName); List<GenTableColumnEntity> tableFieldList = getGenTableColumnEntities(dsName, tableName, tableMetadata);
List<GenTableColumnEntity> tableFieldList = new ArrayList<>();
for (Map<String, String> columnMap : queryColumnList) { // 初始化字段数据
String columnName = MapUtil.getStr(columnMap, "columnName"); columnService.initFieldList(tableFieldList);
// 保存列数据
columnService.saveOrUpdateBatch(tableFieldList);
table.setFieldList(tableFieldList);
return table;
}
/**
* 获取表字段信息
*
* @param dsName 数据源信息
* @param tableName 表名称
* @param tableMetadata 表的元数据
* @return list
*/
private static @NotNull List<GenTableColumnEntity> getGenTableColumnEntities(String dsName, String tableName,
Table tableMetadata) {
List<GenTableColumnEntity> tableFieldList = new ArrayList<>();
LinkedHashMap<String, Column> columns = tableMetadata.getColumns();
columns.forEach((columnName, column) -> {
GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity(); GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity();
genTableColumnEntity.setTableName(tableName); genTableColumnEntity.setTableName(tableName);
genTableColumnEntity.setDsName(dsName); genTableColumnEntity.setDsName(dsName);
genTableColumnEntity.setFieldName(MapUtil.getStr(columnMap, "columnName")); genTableColumnEntity.setFieldName(column.getName());
genTableColumnEntity.setFieldComment(MapUtil.getStr(columnMap, "comments")); genTableColumnEntity.setFieldComment(column.getComment());
genTableColumnEntity.setFieldType(MapUtil.getStr(columnMap, "dataType")); genTableColumnEntity.setFieldType(column.getTypeName());
String columnKey = MapUtil.getStr(columnMap, "columnKey"); genTableColumnEntity.setPrimaryPk(
genTableColumnEntity.setAutoFill("DEFAULT"); column.isPrimaryKey() == 1 ? BoolFillEnum.TRUE.getValue() : BoolFillEnum.FALSE.getValue());
genTableColumnEntity.setPrimaryPk((StringUtils.isNotBlank(columnKey) && "PRI".equalsIgnoreCase(columnKey)) genTableColumnEntity.setAutoFill(AutoFillEnum.DEFAULT.name());
? BoolFillEnum.TRUE.getValue() : BoolFillEnum.FALSE.getValue());
genTableColumnEntity.setAutoFill("DEFAULT");
genTableColumnEntity.setFormItem(BoolFillEnum.TRUE.getValue()); genTableColumnEntity.setFormItem(BoolFillEnum.TRUE.getValue());
genTableColumnEntity.setGridItem(BoolFillEnum.TRUE.getValue()); genTableColumnEntity.setGridItem(BoolFillEnum.TRUE.getValue());
// 审计字段处理 // 审计字段处理
if (EnumUtil.contains(CommonColumnFiledEnum.class, columnName)) { if (EnumUtil.contains(CommonColumnFiledEnum.class, column.getName())) {
CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(columnName); CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(column.getName());
genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem()); genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem());
genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem()); genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem());
genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill()); genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill());
genTableColumnEntity.setSort(commonColumnFiledEnum.getSort()); genTableColumnEntity.setSort(commonColumnFiledEnum.getSort());
} }
tableFieldList.add(genTableColumnEntity); tableFieldList.add(genTableColumnEntity);
} });
// 初始化字段数据 return tableFieldList;
columnService.initFieldList(tableFieldList);
// 保存列数据
columnService.saveOrUpdateBatch(tableFieldList);
table.setFieldList(tableFieldList);
return table;
} }
} }

View File

@ -16,11 +16,35 @@
*/ */
package com.pig4cloud.pig.codegen.service.impl; package com.pig4cloud.pig.codegen.service.impl;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.smallbun.screw.core.constant.DefaultConstants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.config.PigCodeGenDefaultProperties;
import com.pig4cloud.pig.codegen.entity.GenGroupEntity;
import com.pig4cloud.pig.codegen.entity.GenTemplateEntity; import com.pig4cloud.pig.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity;
import com.pig4cloud.pig.codegen.mapper.GenGroupMapper;
import com.pig4cloud.pig.codegen.mapper.GenTemplateGroupMapper;
import com.pig4cloud.pig.codegen.mapper.GenTemplateMapper; import com.pig4cloud.pig.codegen.mapper.GenTemplateMapper;
import com.pig4cloud.pig.codegen.service.GenTemplateService; import com.pig4cloud.pig.codegen.service.GenTemplateService;
import com.pig4cloud.pig.codegen.util.vo.GenTemplateFileVO;
import com.pig4cloud.pig.common.core.exception.CheckedException;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* 模板 * 模板
@ -28,8 +52,147 @@ import org.springframework.stereotype.Service;
* @author PIG * @author PIG
* @date 2023-02-21 11:08:43 * @date 2023-02-21 11:08:43
*/ */
@Slf4j
@Service @Service
@RequiredArgsConstructor
public class GenTemplateServiceImpl extends ServiceImpl<GenTemplateMapper, GenTemplateEntity> public class GenTemplateServiceImpl extends ServiceImpl<GenTemplateMapper, GenTemplateEntity>
implements GenTemplateService { implements GenTemplateService {
private final GenTemplateGroupMapper genTemplateGroupMapper;
private final GenGroupMapper genGroupMapper;
private final PigCodeGenDefaultProperties defaultProperties;
/**
* 在线更新
*
* @return {@link R }
*/
@Override
@Transactional(rollbackFor = Exception.class)
public R onlineUpdate() {
// 获取 config.json version 文件
Map<String, Object> configAndVersion = getConfigAndVersion();
JSONObject configJsonObj = (JSONObject) configAndVersion.get("configJsonObj");
String versionFile = (String) configAndVersion.get("versionFile");
// 查询出全部的模板组名称
Set<String> cgtmConfigGroupNames = configJsonObj.keySet();
String cgtmConfigGroupName = cgtmConfigGroupNames.iterator().next();
// 根据模板组名称+version 查询是否存在不存在则新增存在跳过
boolean exists = genGroupMapper.exists(Wrappers.<GenGroupEntity>lambdaQuery()
.eq(GenGroupEntity::getGroupName, cgtmConfigGroupName + versionFile));
if (exists) {
return R.failed("已是最新版本,无需更新!");
}
// 插入新的模板组名称 + VERSION, 再解析 config.json group 里面的所有模板
insertTemplateFiles(versionFile, configJsonObj, cgtmConfigGroupName);
return R.ok("更新成功,版本号:" + versionFile);
}
/**
* 检查版本
*
* @return {@link R }
*/
public R checkVersion() {
// 关闭在线更新提示
if (!defaultProperties.isAutoCheckVersion()) {
return R.ok(true);
}
// 获取 config.json version 文件
Map<String, Object> configAndVersion = getConfigAndVersion();
JSONObject configJsonObj = (JSONObject) configAndVersion.get("configJsonObj");
String versionFile = (String) configAndVersion.get("versionFile");
// 查询出全部的模板组名称
Set<String> cgtmConfigGroupNames = configJsonObj.keySet();
String cgtmConfigGroupName = cgtmConfigGroupNames.iterator().next();
// 根据模板组名称+version 查询是否存在不存在则新增存在跳过
boolean exists = genGroupMapper.exists(Wrappers.<GenGroupEntity>lambdaQuery()
.eq(GenGroupEntity::getGroupName, cgtmConfigGroupName + versionFile));
return R.ok(exists);
}
/**
* 获取配置和版本
*
* @return {@link Map }<{@link String }, {@link Object }>
*/
private Map<String, Object> getConfigAndVersion() {
// 获取 config.json version 文件
String configFile = getCGTMFile("config.json");
String versionFile = getCGTMFile("VERSION");
// 解析 config.json
JSONObject configJsonObj = JSONUtil.parseObj(configFile);
// configJsonObj versionFile 放入 Map
Map<String, Object> configAndVersion = new HashMap<>();
configAndVersion.put("configJsonObj", configJsonObj);
configAndVersion.put("versionFile", versionFile);
return configAndVersion;
}
/**
* 插入模板文件
*
* @param version 版本
* @param configJsonObj config.json
* @param groupName 组名称
*/
private void insertTemplateFiles(String version, JSONObject configJsonObj, String groupName) {
// 创建新的 group
GenGroupEntity genGroupEntity = new GenGroupEntity();
genGroupEntity.setGroupName(groupName + version);
genGroupMapper.insert(genGroupEntity);
// 解析json配置文件
List<GenTemplateFileVO> templateFileVOList = configJsonObj.getBeanList(groupName, GenTemplateFileVO.class);
for (GenTemplateFileVO genTemplateFileVO : templateFileVOList) {
// 1. 获取模板文件
String templateFile = getCGTMFile(genTemplateFileVO.getTemplateFile());
// 2. 插入模板文件
GenTemplateEntity genTemplateEntity = new GenTemplateEntity();
genTemplateEntity.setTemplateName(genTemplateFileVO.getTemplateName() + version);
genTemplateEntity.setTemplateDesc(genTemplateFileVO.getTemplateName() + version);
genTemplateEntity.setTemplateCode(templateFile);
genTemplateEntity.setGeneratorPath(genTemplateFileVO.getGeneratorPath());
baseMapper.insert(genTemplateEntity);
// 3. 插入模板组关联
GenTemplateGroupEntity genTemplateGroupEntity = new GenTemplateGroupEntity();
genTemplateGroupEntity.setTemplateId(genTemplateEntity.getId());
genTemplateGroupEntity.setGroupId(genGroupEntity.getId());
genTemplateGroupMapper.insert(genTemplateGroupEntity);
}
}
/**
* 获取 cgtmfile
*
* @param fileName 文件名
* @return {@link String }
*/
private String getCGTMFile(String fileName) {
HttpResponse response = HttpRequest.get(String.format("%s/CGTM/raw/master/%s", DefaultConstants.CGTM_URL, fileName))
.execute();
if (response.getStatus() == HttpStatus.HTTP_OK || StrUtil.isNotBlank(response.body())) {
return response.body();
} else {
log.warn("在线更新模板失败:{} Http Code:{}", fileName, response.getStatus());
throw new CheckedException("在线更新模板失败,任务终止!");
}
}
} }

View File

@ -21,22 +21,22 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.NamingCase;
import cn.hutool.core.util.BooleanUtil; import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject; import com.pig4cloud.pig.codegen.config.PigCodeGenDefaultProperties;
import com.pig4cloud.pig.codegen.entity.GenTable; import com.pig4cloud.pig.codegen.entity.GenTable;
import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity; import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pig.codegen.entity.GenTemplateEntity; import com.pig4cloud.pig.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pig.codegen.service.*; import com.pig4cloud.pig.codegen.service.*;
import com.pig4cloud.pig.codegen.util.VelocityKit; import com.pig4cloud.pig.codegen.util.VelocityKit;
import com.pig4cloud.pig.codegen.util.vo.GroupVo; import com.pig4cloud.pig.codegen.util.vo.GroupVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringBootVersion; import org.springframework.boot.SpringBootVersion;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -56,6 +56,8 @@ import java.util.zip.ZipOutputStream;
@RequiredArgsConstructor @RequiredArgsConstructor
public class GeneratorServiceImpl implements GeneratorService { public class GeneratorServiceImpl implements GeneratorService {
private final PigCodeGenDefaultProperties configurationProperties;
private final GenTableColumnService columnService; private final GenTableColumnService columnService;
private final GenFieldTypeService fieldTypeService; private final GenFieldTypeService fieldTypeService;
@ -64,8 +66,10 @@ public class GeneratorServiceImpl implements GeneratorService {
private final GenGroupService genGroupService; private final GenGroupService genGroupService;
/** /**
* 生成代码zip写出 * 生成代码zip写出
*
* @param tableId * @param tableId
* @param zip 输出流 * @param zip 输出流
*/ */
@ -77,13 +81,11 @@ public class GeneratorServiceImpl implements GeneratorService {
Long style = (Long) dataModel.get("style"); Long style = (Long) dataModel.get("style");
GroupVo groupVo = genGroupService.getGroupVoById(style); GroupVO groupVo = genGroupService.getGroupVoById(style);
List<GenTemplateEntity> templateList = groupVo.getTemplateList(); List<GenTemplateEntity> templateList = groupVo.getTemplateList();
Map<String, Object> generatorConfig = tableService.getGeneratorConfig(); String frontendPath = configurationProperties.getFrontendPath();
JSONObject project = (JSONObject) generatorConfig.get("project"); String backendPath = configurationProperties.getBackendPath();
String frontendPath = project.getStr("frontendPath");
String backendPath = project.getStr("backendPath");
for (GenTemplateEntity template : templateList) { for (GenTemplateEntity template : templateList) {
String templateCode = template.getTemplateCode(); String templateCode = template.getTemplateCode();
@ -105,6 +107,7 @@ public class GeneratorServiceImpl implements GeneratorService {
/** /**
* 表达式优化的预览代码方法 * 表达式优化的预览代码方法
*
* @param tableId * @param tableId
* @return [{模板名称:渲染结果}] * @return [{模板名称:渲染结果}]
*/ */
@ -119,10 +122,8 @@ public class GeneratorServiceImpl implements GeneratorService {
// 获取模板列表Lambda 表达式简化代码 // 获取模板列表Lambda 表达式简化代码
List<GenTemplateEntity> templateList = genGroupService.getGroupVoById(style).getTemplateList(); List<GenTemplateEntity> templateList = genGroupService.getGroupVoById(style).getTemplateList();
Map<String, Object> generatorConfig = tableService.getGeneratorConfig(); String frontendPath = configurationProperties.getFrontendPath();
JSONObject project = (JSONObject) generatorConfig.get("project"); String backendPath = configurationProperties.getBackendPath();
String frontendPath = project.getStr("frontendPath");
String backendPath = project.getStr("backendPath");
return templateList.stream().map(template -> { return templateList.stream().map(template -> {
String templateCode = template.getTemplateCode(); String templateCode = template.getTemplateCode();
@ -146,6 +147,7 @@ public class GeneratorServiceImpl implements GeneratorService {
/** /**
* 目标目录写入渲染结果方法 * 目标目录写入渲染结果方法
*
* @param tableId * @param tableId
*/ */
@Override @Override
@ -166,8 +168,10 @@ public class GeneratorServiceImpl implements GeneratorService {
}); });
} }
/** /**
* 通过 Lambda 表达式优化的获取数据模型方法 * 通过 Lambda 表达式优化的获取数据模型方法
*
* @param tableId 表格 ID * @param tableId 表格 ID
* @return 数据模型 Map 对象 * @return 数据模型 Map 对象
*/ */
@ -190,7 +194,7 @@ public class GeneratorServiceImpl implements GeneratorService {
dataModel.put("isSpringBoot3", isSpringBoot3()); dataModel.put("isSpringBoot3", isSpringBoot3());
dataModel.put("dbType", table.getDbType()); dataModel.put("dbType", table.getDbType());
dataModel.put("package", table.getPackageName()); dataModel.put("package", table.getPackageName());
dataModel.put("packagePath", table.getPackageName().replace(".", File.separator)); dataModel.put("packagePath", table.getPackageName().replace(".", "/"));
dataModel.put("version", table.getVersion()); dataModel.put("version", table.getVersion());
dataModel.put("moduleName", table.getModuleName()); dataModel.put("moduleName", table.getModuleName());
dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName())); dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName()));
@ -214,11 +218,44 @@ public class GeneratorServiceImpl implements GeneratorService {
dataModel.put("backendPath", table.getBackendPath()); dataModel.put("backendPath", table.getBackendPath());
dataModel.put("frontendPath", table.getFrontendPath()); dataModel.put("frontendPath", table.getFrontendPath());
// 设置子表
String childTableName = table.getChildTableName();
if (StrUtil.isNotBlank(childTableName)) {
List<GenTableColumnEntity> childFieldList = columnService.lambdaQuery()
.eq(GenTableColumnEntity::getDsName, table.getDsName())
.eq(GenTableColumnEntity::getTableName, table.getChildTableName())
.list();
dataModel.put("childFieldList", childFieldList);
dataModel.put("childTableName", childTableName);
dataModel.put("mainField", NamingCase.toCamelCase(table.getMainField()));
dataModel.put("childField", NamingCase.toCamelCase(table.getChildField()));
dataModel.put("ChildClassName", NamingCase.toPascalCase(childTableName));
dataModel.put("childClassName", StrUtil.lowerFirst(NamingCase.toPascalCase(childTableName)));
// 设置是否是多租户模式 (判断字段列表中是否包含 tenant_id 字段)
childFieldList.stream().filter(genTableColumnEntity -> genTableColumnEntity.getFieldName().equals("tenant_id"))
.findFirst().ifPresent(columnEntity -> dataModel.put("isChildTenant", true));
}
// 设置是否是多租户模式 (判断字段列表中是否包含 tenant_id 字段)
table.getFieldList().stream().filter(genTableColumnEntity -> genTableColumnEntity.getFieldName().equals("tenant_id"))
.findFirst().ifPresent(columnEntity -> dataModel.put("isTenant", true));
return dataModel; return dataModel;
} }
/**
* 判断当前是否是 SpringBoot3 版本
*
* @return true/fasle
*/
private boolean isSpringBoot3() {
return StrUtil.startWith(SpringBootVersion.getVersion(), "3");
}
/** /**
* 将表字段按照类型分组并存储到数据模型中 * 将表字段按照类型分组并存储到数据模型中
*
* @param dataModel 存储数据的 Map 对象 * @param dataModel 存储数据的 Map 对象
* @param table 表信息对象 * @param table 表信息对象
*/ */
@ -252,12 +289,4 @@ public class GeneratorServiceImpl implements GeneratorService {
dataModel.put("queryList", queryList); dataModel.put("queryList", queryList);
} }
/**
* 判断当前是否是 SpringBoot3 版本
*
* @return true/fasle
*/
private boolean isSpringBoot3() {
return StrUtil.startWith(SpringBootVersion.getVersion(), "3");
}
} }

View File

@ -0,0 +1,12 @@
package com.pig4cloud.pig.codegen.util;
/**
* 字段自动填充 枚举
*
* @author 阿沐 babamu@126.com
*/
public enum AutoFillEnum {
DEFAULT, INSERT, UPDATE, INSERT_UPDATE, CREATE;
}

View File

@ -16,36 +16,36 @@ public enum CommonColumnFiledEnum {
/** /**
* create_by 字段 * create_by 字段
*/ */
create_by("0", "0", "INSERT", 100), create_by("0", "0", AutoFillEnum.INSERT.name(), 100),
/** /**
* create_time 字段 * create_time 字段
*/ */
create_time("0", "0", "INSERT", 101), create_time("0", "0", AutoFillEnum.INSERT.name(), 101),
/** /**
* update_by 字段 * update_by 字段
*/ */
update_by("0", "0", "INSERT_UPDATE", 102), update_by("0", "0", AutoFillEnum.INSERT_UPDATE.name(), 102),
/** /**
* update_time 字段 * update_time 字段
*/ */
update_time("0", "0", "INSERT_UPDATE", 103), update_time("0", "0", AutoFillEnum.INSERT_UPDATE.name(), 103),
/** /**
* del_flag 字段 * del_flag 字段
*/ */
del_flag("0", "0", "DEFAULT", 104), del_flag("0", "0", AutoFillEnum.DEFAULT.name(), 104),
/** /**
* tenant_id 字段 * tenant_id 字段
*/ */
tenant_id("0", "0", "DEFAULT", 105); tenant_id("0", "0", AutoFillEnum.DEFAULT.name(), 105);
/** /**
* 表单是否默认显示 * 表单是否默认显示 1/0
*/ */
private String formItem; private String formItem;
/** /**
* 表格是否默认显示 * 表格是否默认显示 1/0
*/ */
private String gridItem; private String gridItem;

View File

@ -1,16 +1,7 @@
package com.pig4cloud.pig.codegen.util; package com.pig4cloud.pig.codegen.util;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pig.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pig.codegen.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pig.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.datasource.enums.DsJdbcUrlEnum;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import org.springframework.context.ApplicationContext;
import java.util.Map;
/** /**
* 代码生成工具类 * 代码生成工具类
@ -39,37 +30,4 @@ public class GenKit {
return StrUtil.subAfter(packageName, ".", true); return StrUtil.subAfter(packageName, ".", true);
} }
/**
* 获取数据源对应方言的mapper
* @param dsName 数据源名称
* @return GeneratorMapper
*/
public GeneratorMapper getMapper(String dsName) {
// 获取目标数据源数据库类型
GenDatasourceConfMapper datasourceConfMapper = SpringContextHolder.getBean(GenDatasourceConfMapper.class);
GenDatasourceConf datasourceConf = datasourceConfMapper
.selectOne(Wrappers.<GenDatasourceConf>lambdaQuery().eq(GenDatasourceConf::getName, dsName));
String dbConfType;
// 默认MYSQL 数据源
if (datasourceConf == null) {
dbConfType = DsJdbcUrlEnum.MYSQL.getDbName();
}
else {
dbConfType = datasourceConf.getDsType();
}
// 获取全部数据实现
ApplicationContext context = SpringContextHolder.getApplicationContext();
Map<String, GeneratorMapper> beansOfType = context.getBeansOfType(GeneratorMapper.class);
// 根据数据类型选择mapper
for (String key : beansOfType.keySet()) {
if (StrUtil.containsIgnoreCase(key, dbConfType)) {
return beansOfType.get(key);
}
}
throw new IllegalArgumentException("dsName 不合法: " + dsName);
}
} }

View File

@ -0,0 +1,29 @@
package com.pig4cloud.pig.codegen.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 代码生成主题
*
* @author 冷冷
*/
@Getter
@AllArgsConstructor
public enum GeneratorStyleEnum {
VFORM_JSON(1L, "element-plus 风格"),
VFORM_FORM(2L, "uview 风格");
/**
* 对应模板ID
*/
private Long templateId;
/**
* 描述
*/
private String desc;
}

View File

@ -1,21 +0,0 @@
package com.pig4cloud.pig.codegen.util;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public enum GeneratorTypeEnum {
/**
* zip压缩包 0
*/
ZIP_DOWNLOAD("0"),
/**
* 自定义目录 1
*/
CUSTOM_DIRECTORY("1");
private final String value;
}

View File

@ -0,0 +1,25 @@
package com.pig4cloud.pig.codegen.util;
/**
* vform 的通用变量
*
* @author lengleng
* @date 2023/6/5
*/
public interface VFormConfigConsts {
String widgetList = "widgetList";
String groupKey = "groupKey";
String type = "type";
String options = "options";
String span = "span";
String cols = "cols";
String key = "key";
}

View File

@ -0,0 +1,22 @@
package com.pig4cloud.pig.codegen.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* vfrom 字段类型
*
* @author lengleng
* @date 2023/6/5
*/
@Getter
@AllArgsConstructor
public enum VFormTypeEnum {
GRID("grid"),
GRID_COL("grid-col");
private final String type;
}

View File

@ -0,0 +1,95 @@
package com.pig4cloud.pig.codegen.util.vo;
/*
* Copyright (c) 2018-2025, luolin All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: luolin (766488893@qq.com)
*/
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 自动创建表管理
*
* @author luolin
* @date 2022-09-23 21:56:11
*/
@Data
@Schema(description = "自动创建表管理")
public class GenCreateTableVO {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@Schema(description = "主键ID")
private Long id;
/**
* 表名称
*/
@NotBlank(message = "表名称不能为空")
@Schema(description = "表名称")
private String tableName;
/**
* 表注释
*/
@NotBlank(message = "表注释不能为空")
@Schema(description = "表注释")
private String comments;
/**
* 数据源名称
*/
@NotBlank(message = "数据源名称不能为空")
@Schema(description = "数据源名称")
private String dsName;
/**
* 主键策略
*/
@NotBlank(message = "主键策略不能为空")
@Schema(description = "主键策略")
private String pkPolicy;
/**
* 创建人
*/
@Schema(description = "创建人")
private Long createUser;
/**
* 创建时间
*/
@Schema(description = "创建时间")
private LocalDateTime createTime;
/**
* 表字段信息
*/
@Schema(description = "表字段信息")
private String columnsInfo;
/**
* 字段信息
*/
@Schema(description = "字段信息")
private String columnInfo;
}

View File

@ -0,0 +1,37 @@
package com.pig4cloud.pig.codegen.util.vo;
import lombok.Data;
/**
* @author lengleng
* @date 2024/7/13
* <p>
* CGTM 文件路径
* <p>
* {
* "templateName": "Controller",
* "generatorPath": "${backendPath}/src/main/java/${packagePath}/${moduleName}/controller/${ClassName}Controller.java",
* "templateDesc": "后台Controller",
* "templateFile": "temps/Controller"
* },
*/
@Data
public class GenTemplateFileVO {
/**
* 模板名称
*/
private String templateName;
/**
* 路径
*/
private String generatorPath;
/**
* 模板 desc
*/
private String templateDesc;
/**
* 模板文件
*/
private String templateFile;
}

View File

@ -9,7 +9,7 @@ import lombok.Data;
import java.util.List; import java.util.List;
@Data @Data
public class GroupVo { public class GroupVO {
/** /**
* id * id

View File

@ -3,7 +3,7 @@
<mapper namespace="com.pig4cloud.pig.codegen.mapper.GenGroupMapper"> <mapper namespace="com.pig4cloud.pig.codegen.mapper.GenGroupMapper">
<resultMap id="genGroupMap" type="com.pig4cloud.pig.codegen.util.vo.GroupVo"> <resultMap id="genGroupMap" type="com.pig4cloud.pig.codegen.util.vo.GroupVO">
<id property="id" column="group_id"/> <id property="id" column="group_id"/>
<result property="groupName" column="group_name"/> <result property="groupName" column="group_name"/>
<result property="groupDesc" column="group_desc"/> <result property="groupDesc" column="group_desc"/>

View File

@ -38,7 +38,6 @@
<result property="moduleName" column="module_name"/> <result property="moduleName" column="module_name"/>
<result property="functionName" column="function_name"/> <result property="functionName" column="function_name"/>
<result property="formLayout" column="form_layout"/> <result property="formLayout" column="form_layout"/>
<result property="datasourceId" column="datasource_id"/>
<result property="baseclassId" column="baseclass_id"/> <result property="baseclassId" column="baseclass_id"/>
<result property="createTime" column="create_time"/> <result property="createTime" column="create_time"/>
</resultMap> </resultMap>

View File

@ -1,48 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pig.codegen.mapper.GeneratorMysqlMapper">
<select id="queryTable" resultType="map">
SELECT
'mysql' AS dbType,
table_name AS tableName,
ENGINE,
table_comment AS tableComment,
create_time AS createTime
FROM
information_schema.TABLES
WHERE
table_schema = (
SELECT DATABASE
())
<if test="tableName != null and tableName.trim() != ''">
and table_name = #{tableName}
</if>
order by create_time desc
</select>
<sql id="queryColumn">
SELECT
column_name columnName,
data_type dataType,
column_comment comments,
column_key columnKey,
extra,
is_nullable AS isNullable,
column_type AS columnType
FROM
information_schema.COLUMNS
WHERE
table_name = #{tableName} and table_schema = (select database()) order by ordinal_position
</sql>
<select id="selectTableColumn" resultType="com.pig4cloud.pig.codegen.entity.ColumnEntity">
<include refid="queryColumn"/>
</select>
<select id="selectMapTableColumn" resultType="map">
<include refid="queryColumn"/>
</select>
</mapper>

View File

@ -1,12 +0,0 @@
{
"project": {
"packageName": "com.pig4cloud.pig",
"version": "1.0.0",
"backendPath": "pig",
"frontendPath": "pig-ui"
},
"developer": {
"author": "pig",
"email": "pig4cloud@qq.com"
}
}