1. 同步数据表和字段定义

2. 删除数据库表
This commit is contained in:
YunaiV 2021-02-11 01:05:21 +08:00
parent 63962d557a
commit 0d55ca747c
16 changed files with 239 additions and 548 deletions

View File

@ -14,6 +14,7 @@ import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "gen")
@PropertySource(value = { "classpath:generator.yml" })
public class GenConfig {
/** 作者 */
public static String author;
@ -26,47 +27,4 @@ public class GenConfig {
/** 表前缀(类名不会包含表前缀) */
public static String tablePrefix;
public static String getAuthor()
{
return author;
}
@Value("${author}")
public void setAuthor(String author)
{
GenConfig.author = author;
}
public static String getPackageName()
{
return packageName;
}
@Value("${packageName}")
public void setPackageName(String packageName)
{
GenConfig.packageName = packageName;
}
public static boolean getAutoRemovePre()
{
return autoRemovePre;
}
@Value("${autoRemovePre}")
public void setAutoRemovePre(boolean autoRemovePre)
{
GenConfig.autoRemovePre = autoRemovePre;
}
public static String getTablePrefix()
{
return tablePrefix;
}
@Value("${tablePrefix}")
public void setTablePrefix(String tablePrefix)
{
GenConfig.tablePrefix = tablePrefix;
}
}

View File

@ -1,114 +0,0 @@
package com.ruoyi.generator.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.service.IGenTableColumnService;
import com.ruoyi.generator.service.IGenTableService;
/**
* 代码生成 操作处理
*
* @author ruoyi
*/
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {
/**
* 查询数据表字段列表
*/
@PreAuthorize("@ss.hasPermi('tool:gen:list')")
@GetMapping(value = "/column/{talbleId}")
public TableDataInfo columnList(Long tableId) {
TableDataInfo dataInfo = new TableDataInfo();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
dataInfo.setRows(list);
dataInfo.setTotal(list.size());
return dataInfo;
}
/**
* 导入表结构保存
*/
@PreAuthorize("@ss.hasPermi('tool:gen:list')")
@Log(title = "代码生成", businessType = BusinessType.IMPORT)
@PostMapping("/importTable")
public AjaxResult importTableSave(String tables) {
String[] tableNames = Convert.toStrArray(tables);
// 查询表信息
List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
genTableService.importGenTable(tableList);
return AjaxResult.success();
}
/**
* 删除代码生成
*/
@PreAuthorize("@ss.hasPermi('tool:gen:remove')")
@Log(title = "代码生成", businessType = BusinessType.DELETE)
@DeleteMapping("/{tableIds}")
public AjaxResult remove(@PathVariable Long[] tableIds) {
genTableService.deleteGenTableByIds(tableIds);
return AjaxResult.success();
}
/**
* 生成代码自定义路径
*/
@PreAuthorize("@ss.hasPermi('tool:gen:code')")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/genCode/{tableName}")
public AjaxResult genCode(@PathVariable("tableName") String tableName) {
genTableService.generatorCode(tableName);
return AjaxResult.success();
}
/**
* 同步数据库
*/
@PreAuthorize("@ss.hasPermi('tool:gen:edit')")
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
@GetMapping("/synchDb/{tableName}")
public AjaxResult synchDb(@PathVariable("tableName") String tableName) {
genTableService.synchDb(tableName);
return AjaxResult.success();
}
/**
* 生成zip文件
*/
private void genCode(HttpServletResponse response, byte[] data) throws IOException {
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
}
}

View File

@ -1,53 +0,0 @@
package com.ruoyi.generator.mapper;
import java.util.List;
import com.ruoyi.generator.domain.GenTable;
/**
* 业务 数据层
*
* @author ruoyi
*/
public interface GenTableMapper {
/**
* 查询业务列表
*
* @param genTable 业务信息
* @return 业务集合
*/
public List<GenTable> selectGenTableList(GenTable genTable);
/**
* 查询据库列表
*
* @param genTable 业务信息
* @return 数据库表集合
*/
public List<GenTable> selectDbTableList(GenTable genTable);
/**
* 查询据库列表
*
* @param tableNames 表名称组
* @return 数据库表集合
*/
public List<GenTable> selectDbTableListByNames(String[] tableNames);
/**
* 查询表ID业务信息
*
* @param id 业务ID
* @return 业务信息
*/
public GenTable selectGenTableById(Long id);
/**
* 查询表名称业务信息
*
* @param tableName 表名称
* @return 业务信息
*/
public GenTable selectGenTableByName(String tableName);
}

View File

@ -1,179 +0,0 @@
package com.ruoyi.generator.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.core.text.CharsetKit;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.mapper.GenTableColumnMapper;
import com.ruoyi.generator.mapper.GenTableMapper;
import com.ruoyi.generator.util.GenUtils;
import com.ruoyi.generator.util.VelocityInitializer;
import com.ruoyi.generator.util.VelocityUtils;
/**
* 业务 服务层实现
*
* @author ruoyi
*/
@Service
public class GenTableServiceImpl implements IGenTableService {
@Autowired
private GenTableMapper genTableMapper;
@Autowired
private GenTableColumnMapper genTableColumnMapper;
/**
* 查询业务信息
*
* @param id 业务ID
* @return 业务信息
*/
@Override
public GenTable selectGenTableById(Long id) {
GenTable genTable = genTableMapper.selectGenTableById(id);
setTableFromOptions(genTable);
return genTable;
}
/**
* 查询据库列表
*
* @param genTable 业务信息
* @return 数据库表集合
*/
@Override
public List<GenTable> selectDbTableList(GenTable genTable) {
return genTableMapper.selectDbTableList(genTable);
}
/**
* 查询据库列表
*
* @param tableNames 表名称组
* @return 数据库表集合
*/
@Override
public List<GenTable> selectDbTableListByNames(String[] tableNames) {
return genTableMapper.selectDbTableListByNames(tableNames);
}
/**
* 删除业务对象
*
* @param tableIds 需要删除的数据ID
* @return 结果
*/
@Override
@Transactional
public void deleteGenTableByIds(Long[] tableIds) {
genTableMapper.deleteGenTableByIds(tableIds);
genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
}
/**
* 导入表结构
*
* @param tableList 导入表列表
*/
@Override
@Transactional
public void importGenTable(List<GenTable> tableList) {
String operName = SecurityUtils.getUsername();
try {
for (GenTable table : tableList) {
String tableName = table.getTableName();
GenUtils.initTable(table, operName);
int row = genTableMapper.insertGenTable(table);
if (row > 0) {
// 保存列信息
List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
for (GenTableColumn column : genTableColumns) {
GenUtils.initColumnField(column, table);
genTableColumnMapper.insertGenTableColumn(column);
}
}
}
} catch (Exception e) {
throw new CustomException("导入失败:" + e.getMessage());
}
}
/**
* 同步数据库
*
* @param tableName 表名称
*/
@Override
@Transactional
public void synchDb(String tableName) {
GenTable table = genTableMapper.selectGenTableByName(tableName);
List<GenTableColumn> tableColumns = table.getColumns();
List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
dbTableColumns.forEach(column -> {
if (!tableColumnNames.contains(column.getColumnName())) {
GenUtils.initColumnField(column, table);
genTableColumnMapper.insertGenTableColumn(column);
}
});
List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
if (StringUtils.isNotEmpty(delColumns)) {
genTableColumnMapper.deleteGenTableColumns(delColumns);
}
}
/**
* 修改保存参数校验
*
* @param genTable 业务信息
*/
@Override
public void validateEdit(GenTable genTable) {
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
String options = JSON.toJSONString(genTable.getParams());
JSONObject paramsObj = JSONObject.parseObject(options);
if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) {
throw new CustomException("树编码字段不能为空");
} else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
throw new CustomException("树父编码字段不能为空");
} else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) {
throw new CustomException("树名称字段不能为空");
}
}
}
}

View File

@ -1,57 +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.ruoyi.generator.mapper.GenTableMapper">
<select id="selectDbTableList" parameterType="GenTable" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_schema = (select database())
AND table_name NOT LIKE 'qrtz_%' AND table_name NOT LIKE 'gen_%'
AND table_name NOT IN (select table_name from gen_table)
<if test="tableName != null and tableName != ''">
AND lower(table_name) like lower(concat('%', #{tableName}, '%'))
</if>
<if test="tableComment != null and tableComment != ''">
AND lower(table_comment) like lower(concat('%', #{tableComment}, '%'))
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
AND date_format(create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
AND date_format(create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
</select>
<select id="selectDbTableListByNames" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_name NOT LIKE 'qrtz_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database())
and table_name in
<foreach collection="array" item="name" open="(" separator="," close=")">
#{name}
</foreach>
</select>
<select id="selectTableByName" parameterType="String" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_comment <![CDATA[ <> ]]> '' and table_schema = (select database())
and table_name = #{tableName}
</select>
<select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
where t.table_id = #{tableId} order by c.sort
</select>
<select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
where t.table_name = #{tableName} order by c.sort
</select>
</mapper>

View File

@ -1,7 +1,7 @@
import request from '@/utils/request'
// 获得表定义分页
export function getCodeGenTablePage(query) {
export function getCodegenTablePage(query) {
return request({
url: '/tool/codegen/table/page',
method: 'get',
@ -10,7 +10,7 @@ export function getCodeGenTablePage(query) {
}
// 获得表和字段的明细
export function getCodeGenDetail(tableId) {
export function getCodegenDetail(tableId) {
return request({
url: '/tool/codegen/detail?tableId=' + tableId,
method: 'get',
@ -26,6 +26,14 @@ export function updateCodegen(data) {
})
}
// 基于数据库的表结构,同步数据库的表和字段定义
export function syncCodegen(tableId) {
return request({
url: '/tool/codegen/sync?tableId=' + tableId,
method: 'put'
})
}
// 预览生成代码
export function previewCodegen(tableId) {
return request({
@ -42,3 +50,32 @@ export function downloadCodegen(tableId) {
responseType: 'blob'
})
}
// 获得表定义分页
export function getSchemaTableList(query) {
return request({
url: '/tool/codegen/db/table/list',
method: 'get',
params: query
})
}
// 基于数据库的表结构,创建代码生成器的表定义
export function createCodegenList(tableNames) {
return request({
url: '/tool/codegen/create-list',
method: 'post',
headers:{
'Content-type': 'application/x-www-form-urlencoded'
},
data: 'tableNames=' + tableNames
})
}
// 删除数据库的表和字段定义
export function deleteCodegen(tableId) {
return request({
url: '/tool/codegen/delete?tableId=' + tableId,
method: 'delete'
})
}

View File

@ -1,43 +0,0 @@
import request from '@/utils/request'
// 查询db数据库列表
export function listDbTable(query) {
return request({
url: '/tool/gen/db/list',
method: 'get',
params: query
})
}
// 导入表
export function importTable(data) {
return request({
url: '/tool/gen/importTable',
method: 'post',
params: data
})
}
// 删除表数据
export function delTable(tableId) {
return request({
url: '/tool/gen/' + tableId,
method: 'delete'
})
}
// 生成代码(自定义路径)
export function genCode(tableName) {
return request({
url: '/tool/gen/genCode/' + tableName,
method: 'get'
})
}
// 同步数据库
export function synchDb(tableName) {
return request({
url: '/tool/gen/synchDb/' + tableName,
method: 'get'
})
}

View File

@ -126,7 +126,7 @@
</el-card>
</template>
<script>
import { getCodeGenDetail, updateCodegen } from "@/api/tool/codegen";
import { getCodegenDetail, updateCodegen } from "@/api/tool/codegen";
import { listAllSimple as listAllSimpleDictType } from "@/api/system/dict/type";
import { listMenu as getMenuTreeselect } from "@/api/system/menu";
import basicInfoForm from "./basicInfoForm";
@ -161,7 +161,7 @@ export default {
const tableId = this.$route.params && this.$route.params.tableId;
if (tableId) {
//
getCodeGenDetail(tableId).then(res => {
getCodegenDetail(tableId).then(res => {
this.table = res.data.table;
this.columns = res.data.columns;
});

View File

@ -28,18 +28,15 @@
<el-row>
<el-table @row-click="clickRow" ref="table" :data="dbTableList" @selection-change="handleSelectionChange" height="260px">
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="tableSchema" label="数据库" :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="tableName" label="表名称" :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="tableComment" label="表描述" :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="createTime" label="创建时间"></el-table-column>
<el-table-column prop="updateTime" label="更新时间"></el-table-column>
<el-table-column prop="createTime" label="创建时间">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.createTime) }}</span>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
</el-row>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="handleImportTable"> </el-button>
@ -49,7 +46,7 @@
</template>
<script>
import { listDbTable, importTable } from "@/api/tool/gen";
import { getSchemaTableList, createCodegenList } from "@/api/tool/codegen";
export default {
data() {
return {
@ -63,8 +60,6 @@ export default {
dbTableList: [],
//
queryParams: {
pageNum: 1,
pageSize: 10,
tableName: undefined,
tableComment: undefined
}
@ -85,16 +80,12 @@ export default {
},
//
getList() {
listDbTable(this.queryParams).then(res => {
if (res.code === 200) {
this.dbTableList = res.rows;
this.total = res.total;
}
getSchemaTableList(this.queryParams).then(res => {
this.dbTableList = res.data;
});
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1;
this.getList();
},
/** 重置按钮操作 */
@ -104,12 +95,10 @@ export default {
},
/** 导入按钮操作 */
handleImportTable() {
importTable({ tables: this.tables.join(",") }).then(res => {
this.msgSuccess(res.msg);
if (res.code === 200) {
this.visible = false;
this.$emit("ok");
}
createCodegenList(this.tables.join(",")).then(res => {
this.msgSuccess("导入成功");
this.visible = false;
this.$emit("ok");
});
}
}

View File

@ -38,9 +38,6 @@
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleGenTable" v-hasPermi="['tool:gen:code']">生成</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="info" plain icon="el-icon-upload" size="mini" @click="openImportTable" v-hasPermi="['tool:gen:import']">导入</el-button>
</el-col>
@ -85,15 +82,12 @@
</template>
<script>
import { delTable, synchDb } from "@/api/tool/gen";
import { getCodeGenTablePage, previewCodegen, downloadCodegen } from "@/api/tool/codegen";
import { getCodegenTablePage, previewCodegen, downloadCodegen, deleteCodegen, syncCodegen } from "@/api/tool/codegen";
import importTable from "./importTable";
//
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
import {list} from "@/api/system/loginlog";
import {exportOperateLog} from "@/api/system/operatelog";
hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
@ -150,7 +144,7 @@ export default {
/** 查询表集合 */
getList() {
this.loading = true;
getCodeGenTablePage(this.addDateRange(this.queryParams, [
getCodegenTablePage(this.addDateRange(this.queryParams, [
this.dateRange[0] ? this.dateRange[0] + ' 00:00:00' : undefined,
this.dateRange[1] ? this.dateRange[1] + ' 23:59:59' : undefined,
], 'CreateTime')).then(response => {
@ -179,7 +173,7 @@ export default {
cancelButtonText: "取消",
type: "warning"
}).then(function() {
return synchDb(tableName);
return syncCodegen(row.id);
}).then(() => {
this.msgSuccess("同步成功");
})
@ -217,13 +211,13 @@ export default {
},
/** 删除按钮操作 */
handleDelete(row) {
const tableIds = row.tableId || this.ids;
this.$confirm('是否确认删除表编号为"' + tableIds + '"的数据项?', "警告", {
const tableIds = row.id;
this.$confirm('是否确认删除表名称为"' + row.tableName + '"的数据项?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(function() {
return delTable(tableIds);
return deleteCodegen(tableIds);
}).then(() => {
this.getList();
this.msgSuccess("删除成功");

View File

@ -15,6 +15,7 @@ import cn.iocoder.dashboard.modules.tool.dal.dataobject.codegen.ToolCodegenColum
import cn.iocoder.dashboard.modules.tool.dal.dataobject.codegen.ToolCodegenTableDO;
import cn.iocoder.dashboard.modules.tool.dal.dataobject.codegen.ToolSchemaTableDO;
import cn.iocoder.dashboard.modules.tool.service.codegen.ToolCodegenService;
import cn.iocoder.dashboard.util.collection.CollectionUtils;
import cn.iocoder.dashboard.util.servlet.ServletUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
@ -31,6 +32,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static cn.iocoder.dashboard.common.pojo.CommonResult.success;
@ -47,7 +49,7 @@ public class ToolCodegenController {
@GetMapping("/db/table/list")
@ApiImplicitParams({
@ApiImplicitParam(name = "tableName", required = true, example = "yudao", dataTypeClass = String.class),
@ApiImplicitParam(name = "tableComment", required = true, example = "芋道", dataTypeClass = Long.class)
@ApiImplicitParam(name = "tableComment", required = true, example = "芋道", dataTypeClass = String.class)
})
// @PreAuthorize("@ss.hasPermi('tool:gen:list')") TODO 权限
public CommonResult<List<ToolSchemaTableRespVO>> getSchemaTableList(
@ -56,33 +58,35 @@ public class ToolCodegenController {
// 获得数据库自带的表定义列表
List<ToolSchemaTableDO> schemaTables = codegenService.getSchemaTableList(tableName, tableComment);
// 移除在 Codegen 已经存在的
return null;
Set<String> existsTables = CollectionUtils.convertSet(codegenService.getCodeGenTableList(), ToolCodegenTableDO::getTableName);
schemaTables.removeIf(table -> existsTables.contains(table.getTableName()));
return success(ToolCodegenConvert.INSTANCE.convertList04(schemaTables));
}
@ApiOperation("获得表定义分页")
@GetMapping("/table/page")
// TODO 权限 @PreAuthorize("@ss.hasPermi('tool:gen:list')")
public CommonResult<PageResult<ToolCodegenTableRespVO>> getCodeGenTablePage(@Valid ToolCodegenTablePageReqVO pageReqVO) {
PageResult<ToolCodegenTableDO> pageResult = codegenService.getCodeGenTablePage(pageReqVO);
PageResult<ToolCodegenTableDO> pageResult = codegenService.getCodegenTablePage(pageReqVO);
return success(ToolCodegenConvert.INSTANCE.convertPage(pageResult));
}
@ApiOperation("获得表和字段的明细")
@GetMapping("/detail")
@ApiImplicitParam(name = "tableId", required = true, example = "表编号", dataTypeClass = Long.class)
// todo @PreAuthorize("@ss.hasPermi('tool:gen:query')")
public CommonResult<ToolCodegenDetailRespVO> getCodeGenDetail(@RequestParam("tableId") Long tableId) {
ToolCodegenTableDO table = codegenService.getCodeGenTablePage(tableId);
public CommonResult<ToolCodegenDetailRespVO> getCodegenDetail(@RequestParam("tableId") Long tableId) {
ToolCodegenTableDO table = codegenService.getCodegenTablePage(tableId);
List<ToolCodegenColumnDO> columns = codegenService.getCodegenColumnListByTableId(tableId);
// 拼装返回
return success(ToolCodegenConvert.INSTANCE.convert(table, columns));
}
@ApiOperation("基于数据库的表结构,创建代码生成器的表定义")
@PostMapping("/create")
@ApiOperation("基于数据库的表结构,创建代码生成器的表和字段定义")
@PostMapping("/create-list")
// TODO 权限
public CommonResult<Long> createCodeGen(@RequestParam("tableName") String tableName) {
return success(codegenService.createCodegen(tableName));
public CommonResult<List<Long>> createCodegenList(@RequestParam("tableNames") List<String> tableNames) {
return success(codegenService.createCodeGenList(tableNames));
}
@ApiOperation("更新数据库的表和字段定义")
@ -93,6 +97,24 @@ public class ToolCodegenController {
return success(true);
}
@ApiOperation("基于数据库的表结构,同步数据库的表和字段定义")
@PutMapping("/sync")
@ApiImplicitParam(name = "tableId", required = true, example = "表编号", dataTypeClass = Long.class)
// @PreAuthorize("@ss.hasPermi('tool:gen:edit')") TODO 权限
public CommonResult<Boolean> syncCodegen(@RequestParam("tableId") Long tableId) {
codegenService.syncCodegen(tableId);
return success(true);
}
@ApiOperation("删除数据库的表和字段定义")
@DeleteMapping("/delete")
@ApiImplicitParam(name = "tableId", required = true, example = "表编号", dataTypeClass = Long.class)
// @PreAuthorize("@ss.hasPermi('tool:gen:remove')") TODO 权限
public CommonResult<Boolean> deleteCodegen(@RequestParam("tableId") Long tableId) {
codegenService.deleteCodegen(tableId);
return success(true);
}
@ApiOperation("预览生成代码")
@GetMapping("/preview")
@ApiImplicitParam(name = "tableId", required = true, example = "表编号", dataTypeClass = Long.class)
@ -119,4 +141,18 @@ public class ToolCodegenController {
ServletUtils.writeAttachment(response, "codegen.zip", outputStream.toByteArray());
}
// /**
// * 查询数据表字段列表
// */
// @PreAuthorize("@ss.hasPermi('tool:gen:list')")
// @GetMapping(value = "/column/{talbleId}")
// public TableDataInfo columnList(Long tableId) {
// TableDataInfo dataInfo = new TableDataInfo();
// List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
// dataInfo.setRows(list);
// dataInfo.setTotal(list.size());
// return dataInfo;
// }
//
}

View File

@ -6,6 +6,7 @@ import cn.iocoder.dashboard.modules.tool.controller.codegen.vo.ToolCodegenPrevie
import cn.iocoder.dashboard.modules.tool.controller.codegen.vo.ToolCodegenUpdateReqVO;
import cn.iocoder.dashboard.modules.tool.controller.codegen.vo.column.ToolCodegenColumnRespVO;
import cn.iocoder.dashboard.modules.tool.controller.codegen.vo.table.ToolCodegenTableRespVO;
import cn.iocoder.dashboard.modules.tool.controller.codegen.vo.table.ToolSchemaTableRespVO;
import cn.iocoder.dashboard.modules.tool.dal.dataobject.codegen.ToolCodegenColumnDO;
import cn.iocoder.dashboard.modules.tool.dal.dataobject.codegen.ToolCodegenTableDO;
import cn.iocoder.dashboard.modules.tool.dal.dataobject.codegen.ToolSchemaColumnDO;
@ -46,6 +47,8 @@ public interface ToolCodegenConvert {
List<ToolCodegenColumnDO> convertList03(List<ToolCodegenUpdateReqVO.Column> columns);
List<ToolSchemaTableRespVO> convertList04(List<ToolSchemaTableDO> list);
// ========== 其它 ==========
default ToolCodegenDetailRespVO convert(ToolCodegenTableDO table, List<ToolCodegenColumnDO> columns) {

View File

@ -11,9 +11,12 @@ import java.util.List;
public interface ToolCodegenColumnMapper extends BaseMapperX<ToolCodegenColumnDO> {
default List<ToolCodegenColumnDO> selectListByTableId(Long tableId) {
return selectList(new QueryWrapper<ToolCodegenColumnDO>()
.eq("table_id", tableId)
return selectList(new QueryWrapper<ToolCodegenColumnDO>().eq("table_id", tableId)
.orderByAsc("ordinal_position"));
}
default void deleteListByTableId(Long tableId) {
delete(new QueryWrapper<ToolCodegenColumnDO>().eq("table_id", tableId));
}
}

View File

@ -14,8 +14,8 @@ public interface ToolSchemaTableMapper extends BaseMapperX<ToolSchemaTableDO> {
default List<ToolSchemaTableDO> selectList(Collection<String> tableSchemas, String tableName, String tableComment) {
return selectList(new QueryWrapperX<ToolSchemaTableDO>().in("table_schema", tableSchemas)
.eqIfPresent("table_name", tableName)
.eqIfPresent("table_comment", tableComment));
.likeIfPresent("table_name", tableName)
.likeIfPresent("table_comment", tableComment));
}
default List<ToolSchemaTableDO> selectListByTableSchema(String tableSchema) {

View File

@ -21,10 +21,18 @@ public interface ToolCodegenService {
* 基于数据库的表结构创建代码生成器的表定义
*
* @param tableName 表名称
* @return 表定义的编号
* @return 创建的表定义的编号
*/
Long createCodegen(String tableName);
/**
* 基于 {@link #createCodegen(String)} 的批量创建
*
* @param tableNames 表名称数组
* @return 创建的表定义的编号数组
*/
List<Long> createCodeGenList(List<String> tableNames);
/**
* 更新数据库的表和字段定义
*
@ -32,13 +40,27 @@ public interface ToolCodegenService {
*/
void updateCodegen(ToolCodegenUpdateReqVO updateReqVO);
/**
* 基于数据库的表结构同步数据库的表和字段定义
*
* @param tableId 表编号
*/
void syncCodegen(Long tableId);
/**
* 删除数据库的表和字段定义
*
* @param tableId 数据编号
*/
void deleteCodegen(Long tableId);
/**
* 获得表定义分页
*
* @param pageReqVO 分页条件
* @return 表定义分页
*/
PageResult<ToolCodegenTableDO> getCodeGenTablePage(ToolCodegenTablePageReqVO pageReqVO);
PageResult<ToolCodegenTableDO> getCodegenTablePage(ToolCodegenTablePageReqVO pageReqVO);
/**
* 获得表定义
@ -46,7 +68,14 @@ public interface ToolCodegenService {
* @param id 表编号
* @return 表定义
*/
ToolCodegenTableDO getCodeGenTablePage(Long id);
ToolCodegenTableDO getCodegenTablePage(Long id);
/**
* 获得全部表定义
*
* @return 表定义数组
*/
List<ToolCodegenTableDO> getCodeGenTableList();
/**
* 获得指定表的字段定义数组

View File

@ -15,12 +15,16 @@ import cn.iocoder.dashboard.modules.tool.dal.mysql.coegen.ToolCodegenTableMapper
import cn.iocoder.dashboard.modules.tool.dal.mysql.coegen.ToolSchemaColumnMapper;
import cn.iocoder.dashboard.modules.tool.dal.mysql.coegen.ToolSchemaTableMapper;
import cn.iocoder.dashboard.modules.tool.service.codegen.ToolCodegenService;
import cn.iocoder.dashboard.util.collection.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 代码生成 Service 实现类
@ -76,6 +80,15 @@ public class ToolCodegenServiceImpl implements ToolCodegenService {
return table.getId();
}
@Override
@Transactional
public List<Long> createCodeGenList(List<String> tableNames) {
List<Long> ids = new ArrayList<>(tableNames.size());
// 遍历添加虽然效率会低一点但是没必要做成完全批量因为不会这么大量
tableNames.forEach(tableName -> ids.add(createCodegen(tableName)));
return ids;
}
@Override
@Transactional
public void updateCodegen(ToolCodegenUpdateReqVO updateReqVO) {
@ -93,15 +106,70 @@ public class ToolCodegenServiceImpl implements ToolCodegenService {
}
@Override
public PageResult<ToolCodegenTableDO> getCodeGenTablePage(ToolCodegenTablePageReqVO pageReqVO) {
public void syncCodegen(Long tableId) {
// 校验是否已经存在
ToolCodegenTableDO table = codegenTableMapper.selectById(tableId);
if (table == null) {
throw new RuntimeException(""); // TODO
}
// 从数据库中获得数据库表结构
List<ToolSchemaColumnDO> schemaColumns = schemaColumnMapper.selectListByTableName(table.getTableName());
if (CollUtil.isEmpty(schemaColumns)) {
throw new RuntimeException(""); // TODO
}
Set<String> schemaColumnNames = CollectionUtils.convertSet(schemaColumns, ToolSchemaColumnDO::getColumnName);
// 构建 ToolCodegenColumnDO 数组只同步新增的字段
List<ToolCodegenColumnDO> codegenColumns = codegenColumnMapper.selectListByTableId(tableId);
Set<String> codegenColumnNames = CollectionUtils.convertSet(codegenColumns, ToolCodegenColumnDO::getColumnName);
// 移除已经存在的字段
schemaColumns.removeIf(column -> codegenColumnNames.contains(column.getColumnName()));
// 计算需要删除的字段
Set<Long> deleteColumnIds = codegenColumns.stream().filter(column -> !schemaColumnNames.contains(column.getColumnName()))
.map(ToolCodegenColumnDO::getId).collect(Collectors.toSet());
if (CollUtil.isEmpty(schemaColumns) && CollUtil.isEmpty(deleteColumnIds)) {
throw new RuntimeException(""); // TODO
}
// 插入新增的字段
List<ToolCodegenColumnDO> columns = codegenBuilder.buildColumns(schemaColumns);
columns.forEach(column -> {
column.setTableId(table.getId());
codegenColumnMapper.insert(column); // TODO 批量插入
});
// 删除不存在的字段
codegenColumnMapper.deleteBatchIds(deleteColumnIds);
}
@Override
@Transactional
public void deleteCodegen(Long tableId) {
// 校验是否已经存在
if (codegenTableMapper.selectById(tableId) == null) {
throw new RuntimeException(""); // TODO
}
// 删除 table 表定义
codegenTableMapper.deleteById(tableId);
// 删除 column 字段定义
codegenColumnMapper.deleteListByTableId(tableId);
}
@Override
public PageResult<ToolCodegenTableDO> getCodegenTablePage(ToolCodegenTablePageReqVO pageReqVO) {
return codegenTableMapper.selectPage(pageReqVO);
}
@Override
public ToolCodegenTableDO getCodeGenTablePage(Long id) {
public ToolCodegenTableDO getCodegenTablePage(Long id) {
return codegenTableMapper.selectById(id);
}
@Override
public List<ToolCodegenTableDO> getCodeGenTableList() {
return codegenTableMapper.selectList();
}
@Override
public List<ToolCodegenColumnDO> getCodegenColumnListByTableId(Long tableId) {
return codegenColumnMapper.selectListByTableId(tableId);
@ -128,4 +196,24 @@ public class ToolCodegenServiceImpl implements ToolCodegenService {
return schemaTableMapper.selectList(codegenProperties.getDbSchemas(), tableName, tableComment);
}
// /**
// * 修改保存参数校验
// *
// * @param genTable 业务信息
// */
// @Override
// public void validateEdit(GenTable genTable) {
// if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
// String options = JSON.toJSONString(genTable.getParams());
// JSONObject paramsObj = JSONObject.parseObject(options);
// if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) {
// throw new CustomException("树编码字段不能为空");
// } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
// throw new CustomException("树父编码字段不能为空");
// } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) {
// throw new CustomException("树名称字段不能为空");
// }
// }
// }
}