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"?>
<!--
~ 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"
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>
@ -30,12 +14,13 @@
<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>
<!--接口文档-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-swagger</artifactId>
</dependency>
<!--注册中心客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
@ -46,16 +31,17 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--断路器依赖-->
<!--数据操作-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-feign</artifactId>
<artifactId>pig-common-mybatis</artifactId>
</dependency>
<!--数据源-->
<!--动态数据源 数据操作-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-datasource</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
@ -64,30 +50,49 @@
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!--common-->
<!--anyline-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
<groupId>org.anyline</groupId>
<artifactId>anyline-environment-spring-data-jdbc</artifactId>
<version>${anyline.version}</version>
</dependency>
<dependency>
<groupId>org.anyline</groupId>
<artifactId>anyline-data-jdbc-mysql</artifactId>
<version>${anyline.version}</version>
</dependency>
<!--common-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-core</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>${configuration.version}</version>
</dependency>
<!--日志处理-->
<!--swagger-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-log</artifactId>
<artifactId>pig-common-swagger</artifactId>
</dependency>
<!--安全模块-->
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-xss</artifactId>
</dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-security</artifactId>
</dependency>
<dependency>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-log</artifactId>
</dependency>
<!--代码生成模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
@ -101,10 +106,15 @@
</dependency>
<!--生成文档-->
<dependency>
<groupId>io.springboot.plugin</groupId>
<groupId>group.springframework.plugin</groupId>
<artifactId>screw-spring-boot-starter</artifactId>
<version>${screw.version}</version>
</dependency>
<!--web 模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--undertow容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
@ -113,13 +123,9 @@
</dependencies>
<profiles>
<profile>
<id>boot</id>
</profile>
<profile>
<id>cloud</id>
<activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
<build>
@ -127,13 +133,29 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<loaderImplementation>CLASSIC</loaderImplementation>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<configuration>
<skip>false</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>boot</id>
</profile>
</profiles>
</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.feign.annotation.EnablePigFeignClients;
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.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@ -30,6 +31,7 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
*/
@EnableDynamicDataSource
@EnablePigFeignClients
@EnablePigDoc("gen")
@EnableDiscoveryClient
@EnablePigResourceServer
@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.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.smallbun.screw.boot.config.Screw;
import cn.smallbun.screw.boot.properties.ScrewProperties;
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.SpringContextHolder;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.common.xss.core.XssCleanIgnore;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
@ -93,6 +93,7 @@ public class GenDsConfController {
* @return R
*/
@PostMapping
@XssCleanIgnore
public R save(@RequestBody GenDatasourceConf datasourceConf) {
return R.ok(datasourceConfService.saveDsByEnc(datasourceConf));
}
@ -103,6 +104,7 @@ public class GenDsConfController {
* @return R
*/
@PutMapping
@XssCleanIgnore
public R updateById(@RequestBody GenDatasourceConf conf) {
return R.ok(datasourceConfService.updateDsByEnc(conf));
}
@ -133,11 +135,11 @@ public class GenDsConfController {
ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class);
// 生成
byte[] data = screw.documentGeneration(dataSource, screwProperties).toByteArray();
byte[] data = screw.documentGeneration(dsName, dataSource, screwProperties).toByteArray();
response.reset();
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType(ContentType.OCTET_STREAM.getValue());
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
response.setContentType("application/octet-stream");
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.pig4cloud.pig.codegen.entity.GenGroupEntity;
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.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
@ -51,95 +51,106 @@ import java.util.List;
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenGroupController {
private final GenGroupService genGroupService;
private final GenGroupService genGroupService;
/**
* 分页查询
* @param page 分页对象
* @param genGroup 模板分组
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@HasPermission("codegen_group_view")
public R getgenGroupPage(Page page, GenGroupEntity genGroup) {
LambdaQueryWrapper<GenGroupEntity> wrapper = Wrappers.<GenGroupEntity>lambdaQuery()
.like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId())
.like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName, genGroup.getGroupName());
return R.ok(genGroupService.page(page, wrapper));
}
/**
* 分页查询
*
* @param page 分页对象
* @param genGroup 模板分组
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@HasPermission("codegen_group_view")
public R getgenGroupPage(Page page, GenGroupEntity genGroup) {
LambdaQueryWrapper<GenGroupEntity> wrapper = Wrappers.<GenGroupEntity>lambdaQuery()
.like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId())
.like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName, genGroup.getGroupName());
return R.ok(genGroupService.page(page, wrapper));
}
/**
* 通过id查询模板分组
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@HasPermission("codegen_group_view")
public R getById(@PathVariable("id") Long id) {
return R.ok(genGroupService.getGroupVoById(id));
}
/**
* 通过id查询模板分组
*
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@HasPermission("codegen_group_view")
public R getById(@PathVariable("id") Long id) {
return R.ok(genGroupService.getGroupVoById(id));
}
/**
* 新增模板分组
* @param genTemplateGroup 模板分组
* @return R
*/
@Operation(summary = "新增模板分组", description = "新增模板分组")
@SysLog("新增模板分组")
@PostMapping
@HasPermission("codegen_group_add")
public R save(@RequestBody TemplateGroupDTO genTemplateGroup) {
genGroupService.saveGenGroup(genTemplateGroup);
return R.ok();
}
/**
* 新增模板分组
*
* @param genTemplateGroup 模板分组
* @return R
*/
@Operation(summary = "新增模板分组", description = "新增模板分组")
@SysLog("新增模板分组")
@PostMapping
@HasPermission("codegen_group_add")
public R save(@RequestBody TemplateGroupDTO genTemplateGroup) {
genGroupService.saveGenGroup(genTemplateGroup);
return R.ok();
}
/**
* 修改模板分组
* @param groupVo 模板分组
* @return R
*/
@Operation(summary = "修改模板分组", description = "修改模板分组")
@SysLog("修改模板分组")
@PutMapping
@HasPermission("codegen_group_edit")
public R updateById(@RequestBody GroupVo groupVo) {
genGroupService.updateGroupAndTemplateById(groupVo);
return R.ok();
}
/**
* 修改模板分组
*
* @param groupVo 模板分组
* @return R
*/
@Operation(summary = "修改模板分组", description = "修改模板分组")
@SysLog("修改模板分组")
@PutMapping
@HasPermission("codegen_group_edit")
public R updateById(@RequestBody GroupVO groupVo) {
genGroupService.updateGroupAndTemplateById(groupVo);
return R.ok();
}
/**
* 通过id删除模板分组
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组")
@SysLog("通过id删除模板分组")
@DeleteMapping
@HasPermission("codegen_group_del")
public R removeById(@RequestBody Long[] ids) {
genGroupService.delGroupAndTemplate(ids);
return R.ok();
}
/**
* 通过id删除模板分组
*
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组")
@SysLog("通过id删除模板分组")
@DeleteMapping
@HasPermission("codegen_group_del")
public R removeById(@RequestBody Long[] ids) {
genGroupService.delGroupAndTemplate(ids);
return R.ok();
}
/**
* 导出excel 表格
* @param genGroup 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@HasPermission("codegen_group_export")
public List<GenGroupEntity> export(GenGroupEntity genGroup) {
return genGroupService.list(Wrappers.query(genGroup));
}
/**
* 导出excel 表格
*
* @param genGroup 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@HasPermission("codegen_group_export")
public List<GenGroupEntity> export(GenGroupEntity genGroup) {
return genGroupService.list(Wrappers.query(genGroup));
}
@GetMapping("/list")
@Operation(summary = "查询列表", description = "查询列表")
public R list() {
List<GenGroupEntity> list = genGroupService.list();
return R.ok(list);
}
/**
* @return 响应信息主体
*/
@GetMapping("/list")
@Operation(summary = "查询列表", description = "查询列表")
public R list() {
List<GenGroupEntity> list = genGroupService.list(Wrappers.<GenGroupEntity>lambdaQuery()
.orderByDesc(GenGroupEntity::getCreateTime));
return R.ok(list);
}
}

View File

@ -61,31 +61,74 @@ public class GenTableController {
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
public R getTablePage(Page page, GenTable table) {
return R.ok(tableService.list(page, table));
return R.ok(tableService.queryTablePage(page, table));
}
/**
* 通过id查询列属性
* 通过id查询表信息代码生成设置 + + 字段设置
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
public R getById(@PathVariable("id") Long id) {
public R getTable(@PathVariable("id") Long id) {
return R.ok(tableService.getById(id));
}
/**
* 新增列属性
* @param table 列属性
* @return R
* 查询数据源所有表
* @param dsName 数据源
*/
@Operation(summary = "新增列属性", description = "新增列属性")
@SysLog("新增列属性")
@PostMapping
public R save(@RequestBody GenTable table) {
return R.ok(tableService.save(table));
@GetMapping("/list/{dsName}")
public R listTable(@PathVariable("dsName") String dsName) {
return R.ok(tableService.queryTableList(dsName));
}
/**
* 获取表信息
* @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
* @return R
* 修改表字段数据
* @param dsName 数据源
* @param tableName 表名称
* @param tableFieldList 字段列表
*/
@Operation(summary = "通过id删除列属性", description = "通过id删除列属性")
@SysLog("通过id删除列属性")
@DeleteMapping("/{id}")
public R removeById(@PathVariable Long id) {
return R.ok(tableService.removeById(id));
@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();
}
/**
@ -123,54 +167,4 @@ public class GenTableController {
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.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.HasPermission;
import com.pig4cloud.pig.common.xss.core.XssCleanIgnore;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
@ -50,97 +51,132 @@ import java.util.List;
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenTemplateController {
private final GenTemplateService genTemplateService;
private final GenTemplateService genTemplateService;
/**
* 分页查询
* @param page 分页对象
* @param genTemplate 模板
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@HasPermission("codegen_template_view")
public R getgenTemplatePage(Page page, GenTemplateEntity genTemplate) {
LambdaQueryWrapper<GenTemplateEntity> wrapper = Wrappers.<GenTemplateEntity>lambdaQuery()
.like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId())
.like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName,
genTemplate.getTemplateName());
return R.ok(genTemplateService.page(page, wrapper));
}
/**
* 分页查询
*
* @param page 分页对象
* @param genTemplate 模板
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@HasPermission("codegen_template_view")
public R getGenTemplatePage(Page page, GenTemplateEntity genTemplate) {
LambdaQueryWrapper<GenTemplateEntity> wrapper = Wrappers.<GenTemplateEntity>lambdaQuery()
.like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId())
.like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName,
genTemplate.getTemplateName());
return R.ok(genTemplateService.page(page, wrapper));
}
/**
* 查询全部模板
* @return
*/
@Operation(summary = "查询全部", description = "查询全部")
@GetMapping("/list")
@HasPermission("codegen_template_view")
public R list() {
return R.ok(genTemplateService.list(Wrappers.emptyWrapper()));
}
/**
* 查询全部模板
*
* @return
*/
@Operation(summary = "查询全部", description = "查询全部")
@GetMapping("/list")
@HasPermission("codegen_template_view")
public R list() {
return R.ok(genTemplateService.list(Wrappers.<GenTemplateEntity>lambdaQuery()
.orderByDesc(GenTemplateEntity::getCreateTime)));
}
/**
* 通过id查询模板
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@HasPermission("codegen_template_view")
public R getById(@PathVariable("id") Long id) {
return R.ok(genTemplateService.getById(id));
}
/**
* 通过id查询模板
*
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@HasPermission("codegen_template_view")
public R getById(@PathVariable("id") Long id) {
return R.ok(genTemplateService.getById(id));
}
/**
* 新增模板
* @param genTemplate 模板
* @return R
*/
@Operation(summary = "新增模板", description = "新增模板")
@SysLog("新增模板")
@PostMapping
@HasPermission("codegen_template_add")
public R save(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.save(genTemplate));
}
/**
* 新增模板
*
* @param genTemplate 模板
* @return R
*/
@XssCleanIgnore
@Operation(summary = "新增模板", description = "新增模板")
@SysLog("新增模板")
@PostMapping
@HasPermission("codegen_template_add")
public R save(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.save(genTemplate));
}
/**
* 修改模板
* @param genTemplate 模板
* @return R
*/
@Operation(summary = "修改模板", description = "修改模板")
@SysLog("修改模板")
@PutMapping
@HasPermission("codegen_template_edit")
public R updateById(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.updateById(genTemplate));
}
/**
* 修改模板
*
* @param genTemplate 模板
* @return R
*/
@XssCleanIgnore
@Operation(summary = "修改模板", description = "修改模板")
@SysLog("修改模板")
@PutMapping
@HasPermission("codegen_template_edit")
public R updateById(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.updateById(genTemplate));
}
/**
* 通过id删除模板
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板", description = "通过id删除模板")
@SysLog("通过id删除模板")
@DeleteMapping
@HasPermission("codegen_template_del")
public R removeById(@RequestBody Long[] ids) {
return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 通过id删除模板
*
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板", description = "通过id删除模板")
@SysLog("通过id删除模板")
@DeleteMapping
@HasPermission("codegen_template_del")
public R removeById(@RequestBody Long[] ids) {
return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 导出excel 表格
* @param genTemplate 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@HasPermission("codegen_template_export")
public List<GenTemplateEntity> export(GenTemplateEntity genTemplate) {
return genTemplateService.list(Wrappers.query(genTemplate));
}
/**
* 导出excel 表格
*
* @param genTemplate 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@HasPermission("codegen_template_export")
public List<GenTemplateEntity> export(GenTemplateEntity 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

@ -46,59 +46,61 @@ import java.util.zip.ZipOutputStream;
@RequestMapping("/generator")
public class GeneratorController {
private final GeneratorService generatorService;
private final GeneratorService generatorService;
/**
* ZIP 下载生成代码
* @param tableIds 数据表ID
* @param response 流输出对象
*/
@SneakyThrows
@GetMapping("/download")
public void download(String tableIds, HttpServletResponse response) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
/**
* ZIP 下载生成代码
*
* @param tableIds 数据表ID
* @param response 流输出对象
*/
@SneakyThrows
@GetMapping("/download")
public void download(String tableIds, HttpServletResponse response) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.downloadCode(Long.parseLong(tableId), zip);
}
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.downloadCode(Long.parseLong(tableId), zip);
}
IoUtil.close(zip);
IoUtil.close(zip);
// zip压缩包数据
byte[] data = outputStream.toByteArray();
// zip压缩包数据
byte[] data = outputStream.toByteArray();
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), false, data);
}
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), false, data);
}
/**
* 目标目录生成代码
*/
@ResponseBody
@GetMapping("/code")
public R<String> code(String tableIds) throws Exception {
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.generatorCode(Long.valueOf(tableId));
}
/**
* 目标目录生成代码
*/
@ResponseBody
@GetMapping("/code")
public R<String> code(String tableIds) throws Exception {
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.generatorCode(Long.valueOf(tableId));
}
return R.ok();
}
return R.ok();
}
/**
* 预览代码
* @param tableId 表ID
* @return
*/
@SneakyThrows
@GetMapping("/preview")
public List<Map<String, String>> preview(Long tableId) {
return generatorService.preview(tableId);
}
/**
* 预览代码
*
* @param tableId 表ID
* @return
*/
@SneakyThrows
@GetMapping("/preview")
public List<Map<String, String>> preview(Long tableId) {
return generatorService.preview(tableId);
}
}

View File

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

View File

@ -37,73 +37,73 @@ import java.time.LocalDateTime;
@Schema(description = "模板")
public class GenTemplateEntity extends Model<GenTemplateEntity> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键")
private Long id;
/**
* 主键
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键")
private Long id;
/**
* 模板名称
*/
@Schema(description = "模板名称")
private String templateName;
/**
* 模板名称
*/
@Schema(description = "模板名称")
private String templateName;
/**
* 模板路径
*/
@Schema(description = "模板路径")
private String generatorPath;
/**
* 模板路径
*/
@Schema(description = "模板路径")
private String generatorPath;
/**
* 模板描述
*/
@Schema(description = "模板描述")
private String templateDesc;
/**
* 模板描述
*/
@Schema(description = "模板描述")
private String templateDesc;
/**
* 模板代码
*/
@Schema(description = "模板代码")
private String templateCode;
/**
* 模板代码
*/
@Schema(description = "模板代码")
private String templateCode;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
@Schema(description = "修改人")
private String updateBy;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
@Schema(description = "修改人")
private String updateBy;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@Schema(description = "修改时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 修改时间
*/
@Schema(description = "修改时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 删除标识0-正常,1-删除
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除标记,1:已删除,0:正常")
private String delFlag;
/**
* 删除标识0-正常,1-删除
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除标记,1:已删除,0:正常")
private String delFlag;
}

View File

@ -19,7 +19,7 @@ package com.pig4cloud.pig.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
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.Param;
@ -32,6 +32,6 @@ import org.apache.ibatis.annotations.Param;
@Mapper
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.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;
/**
@ -33,7 +33,7 @@ public interface GenGroupService extends IService<GenGroupEntity> {
void saveGenGroup(TemplateGroupDTO genTemplateGroup);
/**
* 删除分组关系
* 删除分组极其关系
* @param ids
*/
void delGroupAndTemplate(Long[] ids);
@ -42,12 +42,12 @@ public interface GenGroupService extends IService<GenGroupEntity> {
* 查询group数据
* @param id
*/
GroupVo getGroupVoById(Long id);
GroupVO getGroupVoById(Long id);
/**
* 更新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> {
/**
* 初始化字段列表
* @param tableFieldList 表字段列表
*/
void initFieldList(List<GenTableColumnEntity> tableFieldList);
/**
* 更新表字段
* @param dsName 数据源名称
* @param tableName 表名称
* @param 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.service.IService;
import com.pig4cloud.pig.codegen.entity.GenTable;
import org.anyline.metadata.Table;
import java.util.List;
import java.util.Map;
/**
* 列属性
@ -33,41 +33,50 @@ import java.util.Map;
*/
public interface GenTableService extends IService<GenTable> {
/**
* 获取默认配置信息
* @return 默认配置信息
*/
Map<String, Object> getGeneratorConfig();
/**
* 分页查询表格列表
* @param page 分页对象
* @param table 查询条件
* @return 表格列表分页结果
*/
IPage list(Page<GenTable> page, GenTable table);
/**
* 查询对应数据源的表
*
* @param page 分页信息
* @param table 查询条件
* @return
*/
IPage queryTablePage(Page<Table> page, GenTable table);
/**
* 根据数据源名称和表名查询或构建表格
* @param dsName 数据源名称
* @param tableName 表名
* @return 查询到的表格信息
*/
GenTable queryOrBuildTable(String dsName, String tableName);
/**
* 查询表信息然后插入到中间表中
*
* @param dsName 数据源
* @param tableName 表名
* @return GenTable
*/
GenTable queryOrBuildTable(String dsName, String tableName);
/**
* 查询指定数据源下的所有表格
* @param dsName 数据源名称
* @return 所有表格的列表
*/
List<Map<String, Object>> queryDsAllTable(String dsName);
/**
* 查询表ddl 语句
*
* @param dsName 数据源名称
* @param tableName 表名称
* @return ddl 语句
* @throws Exception
*/
String queryTableDdl(String dsName, String tableName) throws Exception;
/**
* 查询指定数据源和表名的列信息
* @param dsName 数据源名称
* @param tableName 表名
* @return 列信息列表
*/
List<Map<String, String>> queryColumn(String dsName, String tableName);
/**
* 查询数据源里面的全部表
*
* @param dsName 数据源名称
* @return table
*/
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.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> {
/**
* 检查版本
*
* @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.util.StrUtil;
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.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.creator.druid.DruidConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pig.codegen.mapper.GenDatasourceConfMapper;
@ -49,124 +48,122 @@ import java.sql.SQLException;
@Service
@RequiredArgsConstructor
public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfMapper, GenDatasourceConf>
implements GenDatasourceConfService {
implements GenDatasourceConfService {
private final StringEncryptor stringEncryptor;
private final StringEncryptor stringEncryptor;
private final DefaultDataSourceCreator druidDataSourceCreator;
private final DataSourceCreator hikariDataSourceCreator;
/**
* 保存数据源并且加密
* @param conf
* @return
*/
@Override
public Boolean saveDsByEnc(GenDatasourceConf conf) {
// 校验配置合法性
if (!checkDataSource(conf)) {
return Boolean.FALSE;
}
/**
* 保存数据源并且加密
*
* @param conf
* @return
*/
@Override
public Boolean saveDsByEnc(GenDatasourceConf conf) {
// 校验配置合法性
if (!checkDataSource(conf)) {
return Boolean.FALSE;
}
// 添加动态数据源
addDynamicDataSource(conf);
// 添加动态数据源
addDynamicDataSource(conf);
// 更新数据库配置
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
this.baseMapper.insert(conf);
return Boolean.TRUE;
}
// 更新数据库配置
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
this.baseMapper.insert(conf);
return Boolean.TRUE;
}
/**
* 更新数据源
* @param conf 数据源信息
* @return
*/
@Override
public Boolean updateDsByEnc(GenDatasourceConf conf) {
if (!checkDataSource(conf)) {
return Boolean.FALSE;
}
// 先移除
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName());
/**
* 更新数据源
*
* @param conf 数据源信息
* @return
*/
@Override
public Boolean updateDsByEnc(GenDatasourceConf conf) {
if (!checkDataSource(conf)) {
return Boolean.FALSE;
}
// 先移除
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName());
// 再添加
addDynamicDataSource(conf);
// 再添加
addDynamicDataSource(conf);
// 更新数据库配置
if (StrUtil.isNotBlank(conf.getPassword())) {
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
}
this.baseMapper.updateById(conf);
return Boolean.TRUE;
}
// 更新数据库配置
if (StrUtil.isNotBlank(conf.getPassword())) {
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
}
this.baseMapper.updateById(conf);
return Boolean.TRUE;
}
/**
* 通过数据源名称删除
* @param dsIds 数据源ID
* @return
*/
@Override
public Boolean removeByDsId(Long[] dsIds) {
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
this.baseMapper.selectBatchIds(CollUtil.toList(dsIds))
.forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName()));
this.baseMapper.deleteBatchIds(CollUtil.toList(dsIds));
return Boolean.TRUE;
}
/**
* 通过数据源名称删除
*
* @param dsIds 数据源ID
* @return
*/
@Override
public Boolean removeByDsId(Long[] dsIds) {
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
this.baseMapper.selectBatchIds(CollUtil.toList(dsIds))
.forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName()));
this.baseMapper.deleteBatchIds(CollUtil.toList(dsIds));
return Boolean.TRUE;
}
/**
* 添加动态数据源
* @param conf 数据源信息
*/
@Override
public void addDynamicDataSource(GenDatasourceConf conf) {
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setPoolName(conf.getName());
dataSourceProperty.setUrl(conf.getUrl());
dataSourceProperty.setUsername(conf.getUsername());
dataSourceProperty.setPassword(conf.getPassword());
/**
* 添加动态数据源
*
* @param conf 数据源信息
*/
@Override
public void addDynamicDataSource(GenDatasourceConf conf) {
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setPoolName(conf.getName());
dataSourceProperty.setUrl(conf.getUrl());
dataSourceProperty.setUsername(conf.getUsername());
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.addDataSource(dataSourceProperty.getPoolName(), dataSource);
}
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
}
/**
* 校验数据源配置是否有效
*
* @param conf 数据源信息
* @return 有效/无效
*/
@Override
public Boolean checkDataSource(GenDatasourceConf conf) {
String url;
// JDBC 配置形式
if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) {
url = conf.getUrl();
} else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
// 主机形式 sql server 特殊处理
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
} else {
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
/**
* 校验数据源配置是否有效
* @param conf 数据源信息
* @return 有效/无效
*/
@Override
public Boolean checkDataSource(GenDatasourceConf conf) {
String url;
// JDBC 配置形式
if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) {
url = conf.getUrl();
}
else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
// 主机形式 sql server 特殊处理
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
else {
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
conf.setUrl(url);
conf.setUrl(url);
try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) {
}
catch (SQLException e) {
log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
throw new RuntimeException("数据库配置错误,链接失败");
}
return Boolean.TRUE;
}
try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) {
} catch (SQLException e) {
log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
throw new RuntimeException("数据库配置错误,链接失败");
}
return Boolean.TRUE;
}
}

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.service.GenGroupService;
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 lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -87,7 +87,7 @@ public class GenGroupServiceImpl extends ServiceImpl<GenGroupMapper, GenGroupEnt
* @return
*/
@Override
public GroupVo getGroupVoById(Long id) {
public GroupVO getGroupVoById(Long id) {
return baseMapper.getGroupVoById(id);
}
@ -96,7 +96,7 @@ public class GenGroupServiceImpl extends ServiceImpl<GenGroupMapper, GenGroupEnt
* @param groupVo
*/
@Override
public void updateGroupAndTemplateById(GroupVo groupVo) {
public void updateGroupAndTemplateById(GroupVO groupVo) {
// 1.更新自身
GenGroupEntity groupEntity = new GenGroupEntity();
BeanUtil.copyProperties(groupVo, groupEntity);

View File

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

View File

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

View File

@ -16,11 +16,35 @@
*/
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.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.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.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.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
* @date 2023-02-21 11:08:43
*/
@Slf4j
@Service
@RequiredArgsConstructor
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.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.NamingCase;
import cn.hutool.core.util.BooleanUtil;
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.GenTableColumnEntity;
import com.pig4cloud.pig.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pig.codegen.service.*;
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.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringBootVersion;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -56,208 +56,237 @@ import java.util.zip.ZipOutputStream;
@RequiredArgsConstructor
public class GeneratorServiceImpl implements GeneratorService {
private final GenTableColumnService columnService;
private final PigCodeGenDefaultProperties configurationProperties;
private final GenFieldTypeService fieldTypeService;
private final GenTableColumnService columnService;
private final GenTableService tableService;
private final GenFieldTypeService fieldTypeService;
private final GenGroupService genGroupService;
private final GenTableService tableService;
/**
* 生成代码zip写出
* @param tableId
* @param zip 输出流
*/
@Override
@SneakyThrows
public void downloadCode(Long tableId, ZipOutputStream zip) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
private final GenGroupService genGroupService;
Long style = (Long) dataModel.get("style");
GroupVo groupVo = genGroupService.getGroupVoById(style);
List<GenTemplateEntity> templateList = groupVo.getTemplateList();
/**
* 生成代码zip写出
*
* @param tableId
* @param zip 输出流
*/
@Override
@SneakyThrows
public void downloadCode(Long tableId, ZipOutputStream zip) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
Map<String, Object> generatorConfig = tableService.getGeneratorConfig();
JSONObject project = (JSONObject) generatorConfig.get("project");
String frontendPath = project.getStr("frontendPath");
String backendPath = project.getStr("backendPath");
Long style = (Long) dataModel.get("style");
for (GenTemplateEntity template : templateList) {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
GroupVO groupVo = genGroupService.getGroupVoById(style);
List<GenTemplateEntity> templateList = groupVo.getTemplateList();
dataModel.put("frontendPath", frontendPath);
dataModel.put("backendPath", backendPath);
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
String frontendPath = configurationProperties.getFrontendPath();
String backendPath = configurationProperties.getBackendPath();
// 添加到zip
zip.putNextEntry(new ZipEntry(path));
IoUtil.writeUtf8(zip, false, content);
zip.flush();
zip.closeEntry();
}
for (GenTemplateEntity template : templateList) {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
}
dataModel.put("frontendPath", frontendPath);
dataModel.put("backendPath", backendPath);
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
/**
* 表达式优化的预览代码方法
* @param tableId
* @return [{模板名称:渲染结果}]
*/
@Override
@SneakyThrows
public List<Map<String, String>> preview(Long tableId) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
// 添加到zip
zip.putNextEntry(new ZipEntry(path));
IoUtil.writeUtf8(zip, false, content);
zip.flush();
zip.closeEntry();
}
Long style = (Long) dataModel.get("style");
}
// 获取模板列表Lambda 表达式简化代码
List<GenTemplateEntity> templateList = genGroupService.getGroupVoById(style).getTemplateList();
/**
* 表达式优化的预览代码方法
*
* @param tableId
* @return [{模板名称:渲染结果}]
*/
@Override
@SneakyThrows
public List<Map<String, String>> preview(Long tableId) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
Map<String, Object> generatorConfig = tableService.getGeneratorConfig();
JSONObject project = (JSONObject) generatorConfig.get("project");
String frontendPath = project.getStr("frontendPath");
String backendPath = project.getStr("backendPath");
Long style = (Long) dataModel.get("style");
return templateList.stream().map(template -> {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
// 获取模板列表Lambda 表达式简化代码
List<GenTemplateEntity> templateList = genGroupService.getGroupVoById(style).getTemplateList();
// 预览模式下, 使用相对路径展示
dataModel.put("frontendPath", frontendPath);
dataModel.put("backendPath", backendPath);
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
String frontendPath = configurationProperties.getFrontendPath();
String backendPath = configurationProperties.getBackendPath();
// 使用 map 简化代码
return new HashMap<String, String>(4) {
{
put("code", content);
put("codePath", path);
}
};
}).collect(Collectors.toList());
}
return templateList.stream().map(template -> {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
/**
* 目标目录写入渲染结果方法
* @param tableId
*/
@Override
public void generatorCode(Long tableId) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
Long style = (Long) dataModel.get("style");
// 预览模式下, 使用相对路径展示
dataModel.put("frontendPath", frontendPath);
dataModel.put("backendPath", backendPath);
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
// 获取模板列表Lambda 表达式简化代码
List<GenTemplateEntity> templateList = genGroupService.getGroupVoById(style).getTemplateList();
// 使用 map 简化代码
return new HashMap<String, String>(4) {
{
put("code", content);
put("codePath", path);
}
};
}).collect(Collectors.toList());
}
templateList.forEach(template -> {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
FileUtil.writeUtf8String(content, path);
});
}
/**
* 目标目录写入渲染结果方法
*
* @param tableId
*/
@Override
public void generatorCode(Long tableId) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
Long style = (Long) dataModel.get("style");
/**
* 通过 Lambda 表达式优化的获取数据模型方法
* @param tableId 表格 ID
* @return 数据模型 Map 对象
*/
private Map<String, Object> getDataModel(Long tableId) {
// 获取表格信息
GenTable table = tableService.getById(tableId);
// 获取字段列表
List<GenTableColumnEntity> fieldList = columnService.lambdaQuery()
.eq(GenTableColumnEntity::getDsName, table.getDsName())
.eq(GenTableColumnEntity::getTableName, table.getTableName())
.orderByAsc(GenTableColumnEntity::getSort)
.list();
// 获取模板列表Lambda 表达式简化代码
List<GenTemplateEntity> templateList = genGroupService.getGroupVoById(style).getTemplateList();
table.setFieldList(fieldList);
templateList.forEach(template -> {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
FileUtil.writeUtf8String(content, path);
});
}
// 创建数据模型对象
Map<String, Object> dataModel = new HashMap<>();
// 填充数据模型
dataModel.put("isSpringBoot3", isSpringBoot3());
dataModel.put("dbType", table.getDbType());
dataModel.put("package", table.getPackageName());
dataModel.put("packagePath", table.getPackageName().replace(".", File.separator));
dataModel.put("version", table.getVersion());
dataModel.put("moduleName", table.getModuleName());
dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName()));
dataModel.put("functionName", table.getFunctionName());
dataModel.put("FunctionName", StrUtil.upperFirst(table.getFunctionName()));
dataModel.put("formLayout", table.getFormLayout());
dataModel.put("style", table.getStyle());
dataModel.put("author", table.getAuthor());
dataModel.put("datetime", DateUtil.now());
dataModel.put("date", DateUtil.today());
setFieldTypeList(dataModel, table);
/**
* 通过 Lambda 表达式优化的获取数据模型方法
*
* @param tableId 表格 ID
* @return 数据模型 Map 对象
*/
private Map<String, Object> getDataModel(Long tableId) {
// 获取表格信息
GenTable table = tableService.getById(tableId);
// 获取字段列表
List<GenTableColumnEntity> fieldList = columnService.lambdaQuery()
.eq(GenTableColumnEntity::getDsName, table.getDsName())
.eq(GenTableColumnEntity::getTableName, table.getTableName())
.orderByAsc(GenTableColumnEntity::getSort)
.list();
// 获取导入的包列表
Set<String> importList = fieldTypeService.getPackageByTableId(table.getDsName(), table.getTableName());
dataModel.put("importList", importList);
dataModel.put("tableName", table.getTableName());
dataModel.put("tableComment", table.getTableComment());
dataModel.put("className", StrUtil.lowerFirst(table.getClassName()));
dataModel.put("ClassName", table.getClassName());
dataModel.put("fieldList", table.getFieldList());
table.setFieldList(fieldList);
dataModel.put("backendPath", table.getBackendPath());
dataModel.put("frontendPath", table.getFrontendPath());
return dataModel;
}
// 创建数据模型对象
Map<String, Object> dataModel = new HashMap<>();
/**
* 将表字段按照类型分组并存储到数据模型中
* @param dataModel 存储数据的 Map 对象
* @param table 表信息对象
*/
private void setFieldTypeList(Map<String, Object> dataModel, GenTable table) {
// 按字段类型分组使用 Map 存储不同类型的字段列表
Map<Boolean, List<GenTableColumnEntity>> typeMap = table.getFieldList()
.stream()
.collect(Collectors.partitioningBy(columnEntity -> BooleanUtil.toBoolean(columnEntity.getPrimaryPk())));
// 填充数据模型
dataModel.put("isSpringBoot3", isSpringBoot3());
dataModel.put("dbType", table.getDbType());
dataModel.put("package", table.getPackageName());
dataModel.put("packagePath", table.getPackageName().replace(".", "/"));
dataModel.put("version", table.getVersion());
dataModel.put("moduleName", table.getModuleName());
dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName()));
dataModel.put("functionName", table.getFunctionName());
dataModel.put("FunctionName", StrUtil.upperFirst(table.getFunctionName()));
dataModel.put("formLayout", table.getFormLayout());
dataModel.put("style", table.getStyle());
dataModel.put("author", table.getAuthor());
dataModel.put("datetime", DateUtil.now());
dataModel.put("date", DateUtil.today());
setFieldTypeList(dataModel, table);
// 从分组后的 Map 中获取不同类型的字段列表
List<GenTableColumnEntity> primaryList = typeMap.get(true);
List<GenTableColumnEntity> formList = typeMap.get(false)
.stream()
.filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getFormItem()))
.collect(Collectors.toList());
List<GenTableColumnEntity> gridList = typeMap.get(false)
.stream()
.filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getGridItem()))
.collect(Collectors.toList());
List<GenTableColumnEntity> queryList = typeMap.get(false)
.stream()
.filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getQueryItem()))
.collect(Collectors.toList());
// 获取导入的包列表
Set<String> importList = fieldTypeService.getPackageByTableId(table.getDsName(), table.getTableName());
dataModel.put("importList", importList);
dataModel.put("tableName", table.getTableName());
dataModel.put("tableComment", table.getTableComment());
dataModel.put("className", StrUtil.lowerFirst(table.getClassName()));
dataModel.put("ClassName", table.getClassName());
dataModel.put("fieldList", table.getFieldList());
if (CollUtil.isNotEmpty(primaryList)) {
dataModel.put("pk", primaryList.get(0));
}
dataModel.put("primaryList", primaryList);
dataModel.put("formList", formList);
dataModel.put("gridList", gridList);
dataModel.put("queryList", queryList);
}
dataModel.put("backendPath", table.getBackendPath());
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;
}
/**
* 判断当前是否是 SpringBoot3 版本
*
* @return true/fasle
*/
private boolean isSpringBoot3() {
return StrUtil.startWith(SpringBootVersion.getVersion(), "3");
}
/**
* 将表字段按照类型分组并存储到数据模型中
*
* @param dataModel 存储数据的 Map 对象
* @param table 表信息对象
*/
private void setFieldTypeList(Map<String, Object> dataModel, GenTable table) {
// 按字段类型分组使用 Map 存储不同类型的字段列表
Map<Boolean, List<GenTableColumnEntity>> typeMap = table.getFieldList()
.stream()
.collect(Collectors.partitioningBy(columnEntity -> BooleanUtil.toBoolean(columnEntity.getPrimaryPk())));
// 从分组后的 Map 中获取不同类型的字段列表
List<GenTableColumnEntity> primaryList = typeMap.get(true);
List<GenTableColumnEntity> formList = typeMap.get(false)
.stream()
.filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getFormItem()))
.collect(Collectors.toList());
List<GenTableColumnEntity> gridList = typeMap.get(false)
.stream()
.filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getGridItem()))
.collect(Collectors.toList());
List<GenTableColumnEntity> queryList = typeMap.get(false)
.stream()
.filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getQueryItem()))
.collect(Collectors.toList());
if (CollUtil.isNotEmpty(primaryList)) {
dataModel.put("pk", primaryList.get(0));
}
dataModel.put("primaryList", primaryList);
dataModel.put("formList", formList);
dataModel.put("gridList", gridList);
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("0", "0", "INSERT", 100),
create_by("0", "0", AutoFillEnum.INSERT.name(), 100),
/**
* create_time 字段
*/
create_time("0", "0", "INSERT", 101),
create_time("0", "0", AutoFillEnum.INSERT.name(), 101),
/**
* update_by 字段
*/
update_by("0", "0", "INSERT_UPDATE", 102),
update_by("0", "0", AutoFillEnum.INSERT_UPDATE.name(), 102),
/**
* update_time 字段
*/
update_time("0", "0", "INSERT_UPDATE", 103),
update_time("0", "0", AutoFillEnum.INSERT_UPDATE.name(), 103),
/**
* del_flag 字段
*/
del_flag("0", "0", "DEFAULT", 104),
del_flag("0", "0", AutoFillEnum.DEFAULT.name(), 104),
/**
* tenant_id 字段
*/
tenant_id("0", "0", "DEFAULT", 105);
tenant_id("0", "0", AutoFillEnum.DEFAULT.name(), 105);
/**
* 表单是否默认显示
* 表单是否默认显示 1/0
*/
private String formItem;
/**
* 表格是否默认显示
* 表格是否默认显示 1/0
*/
private String gridItem;

View File

@ -1,16 +1,7 @@
package com.pig4cloud.pig.codegen.util;
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 org.springframework.context.ApplicationContext;
import java.util.Map;
/**
* 代码生成工具类
@ -39,37 +30,4 @@ public class GenKit {
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;
@Data
public class GroupVo {
public class GroupVO {
/**
* id

View File

@ -3,12 +3,12 @@
<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"/>
<result property="groupName" column="group_name"/>
<result property="groupDesc" column="group_desc"/>
<collection property="templateList" ofType="com.pig4cloud.pig.codegen.entity.GenTemplateEntity"
select="com.pig4cloud.pig.codegen.mapper.GenTemplateMapper.listTemplateById" column="group_id">
select="com.pig4cloud.pig.codegen.mapper.GenTemplateMapper.listTemplateById" column="group_id">
</collection>
</resultMap>

View File

@ -23,7 +23,7 @@
<mapper namespace="com.pig4cloud.pig.codegen.mapper.GenTableMapper">
<resultMap id="tableMap" type="com.pig4cloud.pig.codegen.entity.GenTable">
<resultMap id="tableMap" type="com.pig4cloud.pig.codegen.entity.GenTable">
<id property="id" column="id"/>
<result property="tableName" column="table_name"/>
<result property="className" column="class_name"/>
@ -38,8 +38,7 @@
<result property="moduleName" column="module_name"/>
<result property="functionName" column="function_name"/>
<result property="formLayout" column="form_layout"/>
<result property="datasourceId" column="datasource_id"/>
<result property="baseclassId" column="baseclass_id"/>
<result property="createTime" column="create_time"/>
</resultMap>
</resultMap>
</mapper>

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"
}
}