update 同步 代码生成 支持代码生成多数据源统一存储

2.X
疯狂的狮子Li 2 years ago
parent 77709cf400
commit 408778c82d

@ -0,0 +1,45 @@
/*
* Copyright © 2018 organization baomidou
*
* 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.
*/
package com.baomidou.dynamic.datasource.processor.jakarta;
import com.baomidou.dynamic.datasource.processor.DsProcessor;
import jakarta.servlet.http.HttpServletRequest;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* @author TaoYu
* @since 3.6.0
*/
public class DsJakartaHeaderProcessor extends DsProcessor {
/**
* header prefix
*/
private static final String HEADER_PREFIX = "#header";
@Override
public boolean matches(String key) {
return key.startsWith(HEADER_PREFIX);
}
@Override
public String doDetermineDatasource(MethodInvocation invocation, String key) {
HttpServletRequest request = (HttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return request.getHeader(key.substring(8));
}
}

@ -0,0 +1,46 @@
/*
* Copyright © 2018 organization baomidou
*
* 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.
*/
package com.baomidou.dynamic.datasource.processor.jakarta;
import com.baomidou.dynamic.datasource.processor.DsProcessor;
import jakarta.servlet.http.HttpServletRequest;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* @author TaoYu
* @since 3.6.0
*/
public class DsJakartaSessionProcessor extends DsProcessor {
/**
* session
*/
private static final String SESSION_PREFIX = "#session";
@Override
public boolean matches(String key) {
return key.startsWith(SESSION_PREFIX);
}
@Override
public String doDetermineDatasource(MethodInvocation invocation, String key) {
HttpServletRequest request = (HttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return request.getSession().getAttribute(key.substring(9)).toString();
}
}

@ -12,6 +12,8 @@ import javax.sql.DataSource;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/** /**
* *
@ -69,4 +71,11 @@ public class DataBaseHelper {
// find_in_set('100' , '0,100,101') // find_in_set('100' , '0,100,101')
return "find_in_set('%s' , %s) <> 0".formatted(var, var2); return "find_in_set('%s' , %s) <> 0".formatted(var, var2);
} }
/**
*
*/
public static List<String> getDataSourceNameList() {
return new ArrayList<>(DS.getDataSources().keySet());
}
} }

@ -16,11 +16,6 @@ public interface GenConstants {
*/ */
String TPL_TREE = "tree"; String TPL_TREE = "tree";
/**
*
*/
String TPL_SUB = "sub";
/** /**
* *
*/ */
@ -49,57 +44,55 @@ public interface GenConstants {
/** /**
* *
*/ */
String[] COLUMNTYPE_STR = {"char", "varchar", "nvarchar", "varchar2"}; String[] COLUMNTYPE_STR = {"char", "varchar", "enum", "set", "nchar", "nvarchar", "varchar2", "nvarchar2"};
/** /**
* *
*/ */
String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext"}; String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext", "binary", "varbinary", "blob",
"ntext", "image", "bytea"};
/** /**
* *
*/ */
String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp"}; String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp", "year", "interval",
"smalldatetime", "datetime2", "datetimeoffset"};
/** /**
* *
*/ */
String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer", String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer",
"bigint", "float", "double", "decimal"}; "bit", "bigint", "float", "double", "decimal", "numeric", "real", "double precision",
"smallserial", "serial", "bigserial", "money", "smallmoney"};
/** /**
* BO * BO
*/ */
String[] COLUMNNAME_NOT_ADD = {"create_by", "create_time", "del_flag", "update_by", String[] COLUMNNAME_NOT_ADD = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
"update_time", "version"}; "update_time", "version", "tenant_id"};
/** /**
* BO * BO
*/ */
String[] COLUMNNAME_NOT_EDIT = {"create_by", "create_time", "del_flag", "update_by", String[] COLUMNNAME_NOT_EDIT = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
"update_time", "version"}; "update_time", "version", "tenant_id"};
/** /**
* VO * VO
*/ */
String[] COLUMNNAME_NOT_LIST = {"create_by", "create_time", "del_flag", "update_by", String[] COLUMNNAME_NOT_LIST = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
"update_time", "version"}; "update_time", "version", "tenant_id"};
/** /**
* BO * BO
*/ */
String[] COLUMNNAME_NOT_QUERY = {"id", "create_by", "create_time", "del_flag", "update_by", String[] COLUMNNAME_NOT_QUERY = {"id", "create_dept", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark", "version"}; "update_time", "remark", "version", "tenant_id"};
/** /**
* Entity * Entity
*/ */
String[] BASE_ENTITY = {"createBy", "createTime", "updateBy", "updateTime"}; String[] BASE_ENTITY = {"createDept", "createBy", "createTime", "updateBy", "updateTime", "tenantId"};
/**
* Tree
*/
String[] TREE_ENTITY = {"parentName", "parentId", "children"};
/** /**
* *

@ -3,20 +3,21 @@ package org.dromara.gen.controller;
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert; import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R; import org.dromara.common.core.domain.R;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.log.annotation.Log; import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType; import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery; import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo; import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.gen.domain.GenTable; import org.dromara.gen.domain.GenTable;
import org.dromara.gen.domain.GenTableColumn; import org.dromara.gen.domain.GenTableColumn;
import org.dromara.gen.service.IGenTableService; import org.dromara.gen.service.IGenTableService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -29,8 +30,8 @@ import java.util.Map;
*/ */
@Validated @Validated
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/gen")
@RestController @RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController { public class GenController extends BaseController {
private final IGenTableService genTableService; private final IGenTableService genTableService;
@ -47,7 +48,7 @@ public class GenController extends BaseController {
/** /**
* *
* *
* @param tableId * @param tableId ID
*/ */
@SaCheckPermission("tool:gen:query") @SaCheckPermission("tool:gen:query")
@GetMapping(value = "/{tableId}") @GetMapping(value = "/{tableId}")
@ -55,7 +56,7 @@ public class GenController extends BaseController {
GenTable table = genTableService.selectGenTableById(tableId); GenTable table = genTableService.selectGenTableById(tableId);
List<GenTable> tables = genTableService.selectGenTableAll(); List<GenTable> tables = genTableService.selectGenTableAll();
List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId); List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<String, Object>();
map.put("info", table); map.put("info", table);
map.put("rows", list); map.put("rows", list);
map.put("tables", tables); map.put("tables", tables);
@ -74,8 +75,9 @@ public class GenController extends BaseController {
/** /**
* *
* *
* @param tableId * @param tableId ID
*/ */
@SaCheckPermission("tool:gen:list")
@GetMapping(value = "/column/{tableId}") @GetMapping(value = "/column/{tableId}")
public TableDataInfo<GenTableColumn> columnList(Long tableId) { public TableDataInfo<GenTableColumn> columnList(Long tableId) {
TableDataInfo<GenTableColumn> dataInfo = new TableDataInfo<>(); TableDataInfo<GenTableColumn> dataInfo = new TableDataInfo<>();
@ -93,11 +95,11 @@ public class GenController extends BaseController {
@SaCheckPermission("tool:gen:import") @SaCheckPermission("tool:gen:import")
@Log(title = "代码生成", businessType = BusinessType.IMPORT) @Log(title = "代码生成", businessType = BusinessType.IMPORT)
@PostMapping("/importTable") @PostMapping("/importTable")
public R<Void> importTableSave(String tables) { public R<Void> importTableSave(String tables, String dataName) {
String[] tableNames = Convert.toStrArray(tables); String[] tableNames = Convert.toStrArray(tables);
// 查询表信息 // 查询表信息
List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames); List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames, dataName);
genTableService.importGenTable(tableList); genTableService.importGenTable(tableList, dataName);
return R.ok(); return R.ok();
} }
@ -116,7 +118,7 @@ public class GenController extends BaseController {
/** /**
* *
* *
* @param tableIds * @param tableIds ID
*/ */
@SaCheckPermission("tool:gen:remove") @SaCheckPermission("tool:gen:remove")
@Log(title = "代码生成", businessType = BusinessType.DELETE) @Log(title = "代码生成", businessType = BusinessType.DELETE)
@ -129,7 +131,7 @@ public class GenController extends BaseController {
/** /**
* *
* *
* @param tableId * @param tableId ID
*/ */
@SaCheckPermission("tool:gen:preview") @SaCheckPermission("tool:gen:preview")
@GetMapping("/preview/{tableId}") @GetMapping("/preview/{tableId}")
@ -141,53 +143,53 @@ public class GenController extends BaseController {
/** /**
* *
* *
* @param tableName * @param tableId ID
*/ */
@SaCheckPermission("tool:gen:code") @SaCheckPermission("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE) @Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/download/{tableName}") @GetMapping("/download/{tableId}")
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException { public void download(HttpServletResponse response, @PathVariable("tableId") Long tableId) throws IOException {
byte[] data = genTableService.downloadCode(tableName); byte[] data = genTableService.downloadCode(tableId);
genCode(response, data); genCode(response, data);
} }
/** /**
* *
* *
* @param tableName * @param tableId ID
*/ */
@SaCheckPermission("tool:gen:code") @SaCheckPermission("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE) @Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/genCode/{tableName}") @GetMapping("/genCode/{tableId}")
public R<Void> genCode(@PathVariable("tableName") String tableName) { public R<Void> genCode(@PathVariable("tableId") Long tableId) {
genTableService.generatorCode(tableName); genTableService.generatorCode(tableId);
return R.ok(); return R.ok();
} }
/** /**
* *
* *
* @param tableName * @param tableId ID
*/ */
@SaCheckPermission("tool:gen:edit") @SaCheckPermission("tool:gen:edit")
@Log(title = "代码生成", businessType = BusinessType.UPDATE) @Log(title = "代码生成", businessType = BusinessType.UPDATE)
@GetMapping("/synchDb/{tableName}") @GetMapping("/synchDb/{tableId}")
public R<Void> synchDb(@PathVariable("tableName") String tableName) { public R<Void> synchDb(@PathVariable("tableId") Long tableId) {
genTableService.synchDb(tableName); genTableService.synchDb(tableId);
return R.ok(); return R.ok();
} }
/** /**
* *
* *
* @param tables * @param tableIdStr ID
*/ */
@SaCheckPermission("tool:gen:code") @SaCheckPermission("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE) @Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/batchGenCode") @GetMapping("/batchGenCode")
public void batchGenCode(HttpServletResponse response, String tables) throws IOException { public void batchGenCode(HttpServletResponse response, String tableIdStr) throws IOException {
String[] tableNames = Convert.toStrArray(tables); String[] tableIds = Convert.toStrArray(tableIdStr);
byte[] data = genTableService.downloadCode(tableNames); byte[] data = genTableService.downloadCode(tableIds);
genCode(response, data); genCode(response, data);
} }
@ -203,4 +205,13 @@ public class GenController extends BaseController {
response.setContentType("application/octet-stream; charset=UTF-8"); response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), false, data); IoUtil.write(response.getOutputStream(), false, data);
} }
/**
*
*/
@SaCheckPermission("tool:gen:list")
@GetMapping(value = "/getDataNames")
public R<Object> getCurrentDataSourceNameList(){
return R.ok(DataBaseHelper.getDataSourceNameList());
}
} }

@ -4,15 +4,14 @@ import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.ArrayUtils;
import org.dromara.common.core.utils.StringUtils; import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.BaseEntity; import org.dromara.common.mybatis.core.domain.BaseEntity;
import org.dromara.gen.constant.GenConstants; import org.dromara.gen.constant.GenConstants;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List; import java.util.List;
/** /**
@ -32,6 +31,12 @@ public class GenTable extends BaseEntity {
@TableId(value = "table_id") @TableId(value = "table_id")
private Long tableId; private Long tableId;
/**
*
*/
@NotBlank(message = "数据源名称不能为空")
private String dataName;
/** /**
* *
*/ */
@ -112,12 +117,6 @@ public class GenTable extends BaseEntity {
@TableField(exist = false) @TableField(exist = false)
private GenTableColumn pkColumn; private GenTableColumn pkColumn;
/**
*
*/
@TableField(exist = false)
private GenTable subTable;
/** /**
* *
*/ */
@ -171,14 +170,6 @@ public class GenTable extends BaseEntity {
@TableField(exist = false) @TableField(exist = false)
private String parentMenuName; private String parentMenuName;
public boolean isSub() {
return isSub(this.tplCategory);
}
public static boolean isSub(String tplCategory) {
return tplCategory != null && StringUtils.equals(GenConstants.TPL_SUB, tplCategory);
}
public boolean isTree() { public boolean isTree() {
return isTree(this.tplCategory); return isTree(this.tplCategory);
} }
@ -200,10 +191,6 @@ public class GenTable extends BaseEntity {
} }
public static boolean isSuperColumn(String tplCategory, String javaField) { public static boolean isSuperColumn(String tplCategory, String javaField) {
if (isTree(tplCategory)) {
return StringUtils.equalsAnyIgnoreCase(javaField,
ArrayUtils.addAll(GenConstants.TREE_ENTITY, GenConstants.BASE_ENTITY));
}
return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY);
} }
} }

@ -4,13 +4,12 @@ import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.dromara.common.core.utils.StringUtils; import jakarta.validation.constraints.NotBlank;
import org.dromara.common.mybatis.core.domain.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.JdbcType;
import org.dromara.common.core.utils.StringUtils;
import jakarta.validation.constraints.NotBlank; import org.dromara.common.mybatis.core.domain.BaseEntity;
/** /**
* gen_table_column * gen_table_column

@ -1,5 +1,6 @@
package org.dromara.gen.mapper; package org.dromara.gen.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore; import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus; import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
import org.dromara.gen.domain.GenTableColumn; import org.dromara.gen.domain.GenTableColumn;
@ -17,8 +18,10 @@ public interface GenTableColumnMapper extends BaseMapperPlus<GenTableColumn, Gen
* *
* *
* @param tableName * @param tableName
* @param dataName
* @return * @return
*/ */
List<GenTableColumn> selectDbTableColumnsByName(String tableName); @DS("#dataName")
List<GenTableColumn> selectDbTableColumnsByName(String tableName, String dataName);
} }

@ -1,5 +1,6 @@
package org.dromara.gen.mapper; package org.dromara.gen.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore; import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
@ -16,6 +17,12 @@ import java.util.List;
@InterceptorIgnore(dataPermission = "true", tenantLine = "true") @InterceptorIgnore(dataPermission = "true", tenantLine = "true")
public interface GenTableMapper extends BaseMapperPlus<GenTable, GenTable> { public interface GenTableMapper extends BaseMapperPlus<GenTable, GenTable> {
/**
*
*
* @param genTable
* @return
*/
Page<GenTable> selectPageDbTableList(@Param("page") Page<GenTable> page, @Param("genTable") GenTable genTable); Page<GenTable> selectPageDbTableList(@Param("page") Page<GenTable> page, @Param("genTable") GenTable genTable);
/** /**
@ -49,4 +56,6 @@ public interface GenTableMapper extends BaseMapperPlus<GenTable, GenTable> {
*/ */
GenTable selectGenTableByName(String tableName); GenTable selectGenTableByName(String tableName);
@DS("")
List<String> selectTableNameList(String dataName);
} }

@ -3,10 +3,9 @@ package org.dromara.gen.service;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
@ -49,9 +48,8 @@ import java.util.zip.ZipOutputStream;
/** /**
* *
* *
* @author ruoyi * @author Lion Li
*/ */
@DS("#header.datasource")
@Slf4j @Slf4j
@RequiredArgsConstructor @RequiredArgsConstructor
@Service @Service
@ -96,16 +94,19 @@ public class GenTableServiceImpl implements IGenTableService {
private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) { private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) {
Map<String, Object> params = genTable.getParams(); Map<String, Object> params = genTable.getParams();
QueryWrapper<GenTable> wrapper = Wrappers.query(); QueryWrapper<GenTable> wrapper = Wrappers.query();
wrapper.like(StringUtils.isNotBlank(genTable.getTableName()), "lower(table_name)", StringUtils.lowerCase(genTable.getTableName())) wrapper
.eq(StringUtils.isNotEmpty(genTable.getDataName()),"data_name", genTable.getDataName())
.like(StringUtils.isNotBlank(genTable.getTableName()), "lower(table_name)", StringUtils.lowerCase(genTable.getTableName()))
.like(StringUtils.isNotBlank(genTable.getTableComment()), "lower(table_comment)", StringUtils.lowerCase(genTable.getTableComment())) .like(StringUtils.isNotBlank(genTable.getTableComment()), "lower(table_comment)", StringUtils.lowerCase(genTable.getTableComment()))
.between(params.get("beginTime") != null && params.get("endTime") != null, .between(params.get("beginTime") != null && params.get("endTime") != null,
"create_time", params.get("beginTime"), params.get("endTime")); "create_time", params.get("beginTime"), params.get("endTime"));
return wrapper; return wrapper;
} }
@DS("#genTable.dataName")
@Override @Override
public TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery) { public TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery) {
genTable.getParams().put("genTableNames",baseMapper.selectTableNameList(genTable.getDataName()));
Page<GenTable> page = baseMapper.selectPageDbTableList(pageQuery.build(), genTable); Page<GenTable> page = baseMapper.selectPageDbTableList(pageQuery.build(), genTable);
return TableDataInfo.build(page); return TableDataInfo.build(page);
} }
@ -114,10 +115,12 @@ public class GenTableServiceImpl implements IGenTableService {
* *
* *
* @param tableNames * @param tableNames
* @param dataName
* @return * @return
*/ */
@DS("#dataName")
@Override @Override
public List<GenTable> selectDbTableListByNames(String[] tableNames) { public List<GenTable> selectDbTableListByNames(String[] tableNames, String dataName) {
return baseMapper.selectDbTableListByNames(tableNames); return baseMapper.selectDbTableListByNames(tableNames);
} }
@ -135,7 +138,6 @@ public class GenTableServiceImpl implements IGenTableService {
* *
* *
* @param genTable * @param genTable
* @return
*/ */
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@Override @Override
@ -154,7 +156,6 @@ public class GenTableServiceImpl implements IGenTableService {
* *
* *
* @param tableIds ID * @param tableIds ID
* @return
*/ */
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@Override @Override
@ -168,19 +169,21 @@ public class GenTableServiceImpl implements IGenTableService {
* *
* *
* @param tableList * @param tableList
* @param dataName
*/ */
@Transactional(rollbackFor = Exception.class) @DSTransactional
@Override @Override
public void importGenTable(List<GenTable> tableList) { public void importGenTable(List<GenTable> tableList, String dataName) {
Long operId = LoginHelper.getUserId(); Long operId = LoginHelper.getUserId();
try { try {
for (GenTable table : tableList) { for (GenTable table : tableList) {
String tableName = table.getTableName(); String tableName = table.getTableName();
GenUtils.initTable(table, operId); GenUtils.initTable(table, operId);
table.setDataName(dataName);
int row = baseMapper.insert(table); int row = baseMapper.insert(table);
if (row > 0) { if (row > 0) {
// 保存列信息 // 保存列信息
List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName, dataName);
List<GenTableColumn> saveColumns = new ArrayList<>(); List<GenTableColumn> saveColumns = new ArrayList<>();
for (GenTableColumn column : genTableColumns) { for (GenTableColumn column : genTableColumns) {
GenUtils.initColumnField(column, table); GenUtils.initColumnField(column, table);
@ -212,8 +215,6 @@ public class GenTableServiceImpl implements IGenTableService {
menuIds.add(identifierGenerator.nextId(null).longValue()); menuIds.add(identifierGenerator.nextId(null).longValue());
} }
table.setMenuIds(menuIds); table.setMenuIds(menuIds);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息 // 设置主键列信息
setPkColumn(table); setPkColumn(table);
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
@ -235,14 +236,14 @@ public class GenTableServiceImpl implements IGenTableService {
/** /**
* *
* *
* @param tableName * @param tableId
* @return * @return
*/ */
@Override @Override
public byte[] downloadCode(String tableName) { public byte[] downloadCode(Long tableId) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream); ZipOutputStream zip = new ZipOutputStream(outputStream);
generatorCode(tableName, zip); generatorCode(tableId, zip);
IoUtil.close(zip); IoUtil.close(zip);
return outputStream.toByteArray(); return outputStream.toByteArray();
} }
@ -250,19 +251,12 @@ public class GenTableServiceImpl implements IGenTableService {
/** /**
* *
* *
* @param tableName * @param tableId
*/ */
@Override @Override
public void generatorCode(String tableName) { public void generatorCode(Long tableId) {
// 查询表信息 // 查询表信息
GenTable table = baseMapper.selectGenTableByName(tableName); GenTable table = baseMapper.selectGenTableById(tableId);
List<Long> menuIds = new ArrayList<>();
for (int i = 0; i < 6; i++) {
menuIds.add(identifierGenerator.nextId(null).longValue());
}
table.setMenuIds(menuIds);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息 // 设置主键列信息
setPkColumn(table); setPkColumn(table);
@ -273,7 +267,7 @@ public class GenTableServiceImpl implements IGenTableService {
// 获取模板列表 // 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) { for (String template : templates) {
if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) { if (!StringUtils.containsAny(template, "sql.vm", "api.ts.vm", "types.ts.vm", "index.vue.vm", "index-tree.vue.vm")) {
// 渲染模板 // 渲染模板
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8); Template tpl = Velocity.getTemplate(template, Constants.UTF8);
@ -291,17 +285,16 @@ public class GenTableServiceImpl implements IGenTableService {
/** /**
* *
* *
* @param tableName * @param tableId
*/ */
@Transactional(rollbackFor = Exception.class) @DSTransactional
@Override @Override
public void synchDb(String tableName) { public void synchDb(Long tableId) {
GenTable table = baseMapper.selectGenTableById(tableId);
GenTable table = baseMapper.selectGenTableByName(tableName);
List<GenTableColumn> tableColumns = table.getColumns(); List<GenTableColumn> tableColumns = table.getColumns();
Map<String, GenTableColumn> tableColumnMap = StreamUtils.toIdentityMap(tableColumns, GenTableColumn::getColumnName); Map<String, GenTableColumn> tableColumnMap = StreamUtils.toIdentityMap(tableColumns, GenTableColumn::getColumnName);
List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(table.getTableName(), table.getDataName());
if (CollUtil.isEmpty(dbTableColumns)) { if (CollUtil.isEmpty(dbTableColumns)) {
throw new ServiceException("同步数据失败,原表结构不存在"); throw new ServiceException("同步数据失败,原表结构不存在");
} }
@ -328,30 +321,30 @@ public class GenTableServiceImpl implements IGenTableService {
} }
saveColumns.add(column); saveColumns.add(column);
}); });
if (CollUtil.isNotEmpty(saveColumns)) { if (CollUtil.isNotEmpty(saveColumns)) {
genTableColumnMapper.insertOrUpdateBatch(saveColumns); genTableColumnMapper.insertOrUpdateBatch(saveColumns);
} }
List<GenTableColumn> delColumns = StreamUtils.filter(tableColumns, column -> !dbTableColumnNames.contains(column.getColumnName())); List<GenTableColumn> delColumns = StreamUtils.filter(tableColumns, column -> !dbTableColumnNames.contains(column.getColumnName()));
if (CollUtil.isNotEmpty(delColumns)) { if (CollUtil.isNotEmpty(delColumns)) {
List<Long> ids = StreamUtils.toList(delColumns, GenTableColumn::getColumnId); List<Long> ids = StreamUtils.toList(delColumns, GenTableColumn::getColumnId);
if (CollUtil.isNotEmpty(ids)) {
genTableColumnMapper.deleteBatchIds(ids); genTableColumnMapper.deleteBatchIds(ids);
} }
} }
}
/** /**
* *
* *
* @param tableNames * @param tableIds ID
* @return * @return
*/ */
@Override @Override
public byte[] downloadCode(String[] tableNames) { public byte[] downloadCode(String[] tableIds) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream); ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) { for (String tableId : tableIds) {
generatorCode(tableName, zip); generatorCode(Long.parseLong(tableId), zip);
} }
IoUtil.close(zip); IoUtil.close(zip);
return outputStream.toByteArray(); return outputStream.toByteArray();
@ -360,17 +353,14 @@ public class GenTableServiceImpl implements IGenTableService {
/** /**
* *
*/ */
private void generatorCode(String tableName, ZipOutputStream zip) { private void generatorCode(Long tableId, ZipOutputStream zip) {
// 查询表信息 // 查询表信息
GenTable table = baseMapper.selectGenTableByName(tableName); GenTable table = baseMapper.selectGenTableById(tableId);
Snowflake snowflake = IdUtil.getSnowflake();
List<Long> menuIds = new ArrayList<>(); List<Long> menuIds = new ArrayList<>();
for (int i = 0; i < 6; i++) { for (int i = 0; i < 6; i++) {
menuIds.add(snowflake.nextId()); menuIds.add(identifierGenerator.nextId(null).longValue());
} }
table.setMenuIds(menuIds); table.setMenuIds(menuIds);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息 // 设置主键列信息
setPkColumn(table); setPkColumn(table);
@ -414,12 +404,6 @@ public class GenTableServiceImpl implements IGenTableService {
throw new ServiceException("树父编码字段不能为空"); throw new ServiceException("树父编码字段不能为空");
} else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_NAME))) { } else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_NAME))) {
throw new ServiceException("树名称字段不能为空"); throw new ServiceException("树名称字段不能为空");
} else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) {
if (StringUtils.isEmpty(genTable.getSubTableName())) {
throw new ServiceException("关联子表的表名不能为空");
} else if (StringUtils.isEmpty(genTable.getSubTableFkName())) {
throw new ServiceException("子表关联的外键名不能为空");
}
} }
} }
} }
@ -439,29 +423,7 @@ public class GenTableServiceImpl implements IGenTableService {
if (ObjectUtil.isNull(table.getPkColumn())) { if (ObjectUtil.isNull(table.getPkColumn())) {
table.setPkColumn(table.getColumns().get(0)); table.setPkColumn(table.getColumns().get(0));
} }
if (GenConstants.TPL_SUB.equals(table.getTplCategory())) {
for (GenTableColumn column : table.getSubTable().getColumns()) {
if (column.isPk()) {
table.getSubTable().setPkColumn(column);
break;
}
}
if (ObjectUtil.isNull(table.getSubTable().getPkColumn())) {
table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
}
}
}
/**
*
*
* @param table
*/
public void setSubTable(GenTable table) {
String subTableName = table.getSubTableName();
if (StringUtils.isNotEmpty(subTableName)) {
table.setSubTable(baseMapper.selectGenTableByName(subTableName));
}
} }
/** /**
@ -501,3 +463,4 @@ public class GenTableServiceImpl implements IGenTableService {
return genPath + File.separator + VelocityUtils.getFileName(template, table); return genPath + File.separator + VelocityUtils.getFileName(template, table);
} }
} }

@ -11,7 +11,7 @@ import java.util.Map;
/** /**
* *
* *
* @author ruoyi * @author Lion Li
*/ */
public interface IGenTableService { public interface IGenTableService {
@ -23,17 +23,30 @@ public interface IGenTableService {
*/ */
List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId); List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId);
/**
*
*
* @param genTable
* @return
*/
TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery); TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery);
/**
*
*
* @param genTable
* @return
*/
TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery); TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery);
/** /**
* *
* *
* @param tableNames * @param tableNames
* @param dataName
* @return * @return
*/ */
List<GenTable> selectDbTableListByNames(String[] tableNames); List<GenTable> selectDbTableListByNames(String[] tableNames, String dataName);
/** /**
* *
@ -54,7 +67,6 @@ public interface IGenTableService {
* *
* *
* @param genTable * @param genTable
* @return
*/ */
void updateGenTable(GenTable genTable); void updateGenTable(GenTable genTable);
@ -62,7 +74,6 @@ public interface IGenTableService {
* *
* *
* @param tableIds ID * @param tableIds ID
* @return
*/ */
void deleteGenTableByIds(Long[] tableIds); void deleteGenTableByIds(Long[] tableIds);
@ -70,8 +81,9 @@ public interface IGenTableService {
* *
* *
* @param tableList * @param tableList
* @param dataName
*/ */
void importGenTable(List<GenTable> tableList); void importGenTable(List<GenTable> tableList, String dataName);
/** /**
* *
@ -84,33 +96,32 @@ public interface IGenTableService {
/** /**
* *
* *
* @param tableName * @param tableId
* @return * @return
*/ */
byte[] downloadCode(String tableName); byte[] downloadCode(Long tableId);
/** /**
* *
* *
* @param tableName * @param tableId
* @return
*/ */
void generatorCode(String tableName); void generatorCode(Long tableId);
/** /**
* *
* *
* @param tableName * @param tableId
*/ */
void synchDb(String tableName); void synchDb(Long tableId);
/** /**
* *
* *
* @param tableNames * @param tableIds ID
* @return * @return
*/ */
byte[] downloadCode(String[] tableNames); byte[] downloadCode(String[] tableIds);
/** /**
* *

@ -18,6 +18,7 @@ import java.util.Arrays;
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class GenUtils { public class GenUtils {
/** /**
* *
*/ */
@ -177,7 +178,6 @@ public class GenUtils {
* *
* @param replacementm * @param replacementm
* @param searchList * @param searchList
* @return
*/ */
public static String replaceFirst(String replacementm, String[] searchList) { public static String replaceFirst(String replacementm, String[] searchList) {
String text = replacementm; String text = replacementm;

@ -1,9 +1,9 @@
package org.dromara.gen.util; package org.dromara.gen.util;
import org.dromara.common.core.constant.Constants;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import org.apache.velocity.app.Velocity; import org.apache.velocity.app.Velocity;
import org.dromara.common.core.constant.Constants;
import java.util.Properties; import java.util.Properties;
@ -14,6 +14,7 @@ import java.util.Properties;
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class VelocityInitializer { public class VelocityInitializer {
/** /**
* vm * vm
*/ */
@ -30,4 +31,5 @@ public class VelocityInitializer {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }

@ -3,7 +3,6 @@ package org.dromara.gen.util;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert; import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
@ -18,7 +17,7 @@ import org.dromara.gen.domain.GenTableColumn;
import java.util.*; import java.util.*;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@ -75,9 +74,6 @@ public class VelocityUtils {
if (GenConstants.TPL_TREE.equals(tplCategory)) { if (GenConstants.TPL_TREE.equals(tplCategory)) {
setTreeVelocityContext(velocityContext, genTable); setTreeVelocityContext(velocityContext, genTable);
} }
if (GenConstants.TPL_SUB.equals(tplCategory)) {
setSubVelocityContext(velocityContext, genTable);
}
return velocityContext; return velocityContext;
} }
@ -107,33 +103,16 @@ public class VelocityUtils {
} }
} }
public static void setSubVelocityContext(VelocityContext context, GenTable genTable) {
GenTable subTable = genTable.getSubTable();
String subTableName = genTable.getSubTableName();
String subTableFkName = genTable.getSubTableFkName();
String subClassName = genTable.getSubTable().getClassName();
String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName);
context.put("subTable", subTable);
context.put("subTableName", subTableName);
context.put("subTableFkName", subTableFkName);
context.put("subTableFkClassName", subTableFkClassName);
context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
context.put("subClassName", subClassName);
context.put("subclassName", StringUtils.uncapitalize(subClassName));
context.put("subImportList", getImportList(genTable.getSubTable()));
}
/** /**
* *
* *
* @return * @return
*/ */
public static List<String> getTemplateList(String tplCategory) { public static List<String> getTemplateList(String tplCategory) {
List<String> templates = new ArrayList<>(); List<String> templates = new ArrayList<String>();
templates.add("vm/java/domain.java.vm"); templates.add("vm/java/domain.java.vm");
templates.add("vm/java/bo.java.vm");
templates.add("vm/java/vo.java.vm"); templates.add("vm/java/vo.java.vm");
templates.add("vm/java/bo.java.vm");
templates.add("vm/java/mapper.java.vm"); templates.add("vm/java/mapper.java.vm");
templates.add("vm/java/service.java.vm"); templates.add("vm/java/service.java.vm");
templates.add("vm/java/serviceImpl.java.vm"); templates.add("vm/java/serviceImpl.java.vm");
@ -146,14 +125,12 @@ public class VelocityUtils {
} else { } else {
templates.add("vm/sql/sql.vm"); templates.add("vm/sql/sql.vm");
} }
templates.add("vm/js/api.js.vm"); templates.add("vm/ts/api.ts.vm");
templates.add("vm/ts/types.ts.vm");
if (GenConstants.TPL_CRUD.equals(tplCategory)) { if (GenConstants.TPL_CRUD.equals(tplCategory)) {
templates.add("vm/vue/index.vue.vm"); templates.add("vm/vue/index.vue.vm");
} else if (GenConstants.TPL_TREE.equals(tplCategory)) { } else if (GenConstants.TPL_TREE.equals(tplCategory)) {
templates.add("vm/vue/index-tree.vue.vm"); templates.add("vm/vue/index-tree.vue.vm");
} else if (GenConstants.TPL_SUB.equals(tplCategory)) {
templates.add("vm/vue/index.vue.vm");
templates.add("vm/java/sub-domain.java.vm");
} }
return templates; return templates;
} }
@ -186,9 +163,7 @@ public class VelocityUtils {
if (template.contains("bo.java.vm")) { if (template.contains("bo.java.vm")) {
fileName = StringUtils.format("{}/domain/bo/{}Bo.java", javaPath, className); fileName = StringUtils.format("{}/domain/bo/{}Bo.java", javaPath, className);
} }
if (template.contains("sub-domain.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) { if (template.contains("mapper.java.vm")) {
fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName());
} else if (template.contains("mapper.java.vm")) {
fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
} else if (template.contains("service.java.vm")) { } else if (template.contains("service.java.vm")) {
fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className); fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className);
@ -200,8 +175,10 @@ public class VelocityUtils {
fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
} else if (template.contains("sql.vm")) { } else if (template.contains("sql.vm")) {
fileName = businessName + "Menu.sql"; fileName = businessName + "Menu.sql";
} else if (template.contains("api.js.vm")) { } else if (template.contains("api.ts.vm")) {
fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName); fileName = StringUtils.format("{}/api/{}/{}/index.ts", vuePath, moduleName, businessName);
} else if (template.contains("types.ts.vm")) {
fileName = StringUtils.format("{}/api/{}/{}/types.ts", vuePath, moduleName, businessName);
} else if (template.contains("index.vue.vm")) { } else if (template.contains("index.vue.vm")) {
fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
} else if (template.contains("index-tree.vue.vm")) { } else if (template.contains("index-tree.vue.vm")) {
@ -229,14 +206,11 @@ public class VelocityUtils {
*/ */
public static HashSet<String> getImportList(GenTable genTable) { public static HashSet<String> getImportList(GenTable genTable) {
List<GenTableColumn> columns = genTable.getColumns(); List<GenTableColumn> columns = genTable.getColumns();
GenTable subGenTable = genTable.getSubTable();
HashSet<String> importList = new HashSet<>(); HashSet<String> importList = new HashSet<>();
if (ObjectUtil.isNotNull(subGenTable)) {
importList.add("java.util.List");
}
for (GenTableColumn column : columns) { for (GenTableColumn column : columns) {
if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) { if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
importList.add("java.util.Date"); importList.add("java.util.Date");
importList.add("com.fasterxml.jackson.annotation.JsonFormat");
} else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) { } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
importList.add("java.math.BigDecimal"); importList.add("java.math.BigDecimal");
} }
@ -254,10 +228,6 @@ public class VelocityUtils {
List<GenTableColumn> columns = genTable.getColumns(); List<GenTableColumn> columns = genTable.getColumns();
Set<String> dicts = new HashSet<>(); Set<String> dicts = new HashSet<>();
addDicts(dicts, columns); addDicts(dicts, columns);
if (ObjectUtil.isNotNull(genTable.getSubTable())) {
List<GenTableColumn> subColumns = genTable.getSubTable().getColumns();
addDicts(dicts, subColumns);
}
return StringUtils.join(dicts, ", "); return StringUtils.join(dicts, ", ");
} }

@ -4,29 +4,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.gen.mapper.GenTableColumnMapper"> <mapper namespace="org.dromara.gen.mapper.GenTableColumnMapper">
<resultMap type="GenTableColumn" id="GenTableColumnResult"> <resultMap type="org.dromara.gen.domain.GenTableColumn" id="GenTableColumnResult">
<id property="columnId" column="column_id" />
<result property="tableId" column="table_id" />
<result property="columnName" column="column_name" />
<result property="columnComment" column="column_comment" />
<result property="columnType" column="column_type" />
<result property="javaType" column="java_type" />
<result property="javaField" column="java_field" />
<result property="isPk" column="is_pk" />
<result property="isIncrement" column="is_increment" />
<result property="isRequired" column="is_required" />
<result property="isInsert" column="is_insert" />
<result property="isEdit" column="is_edit" />
<result property="isList" column="is_list" />
<result property="isQuery" column="is_query" />
<result property="queryType" column="query_type" />
<result property="htmlType" column="html_type" />
<result property="dictType" column="dict_type" />
<result property="sort" column="sort" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap> </resultMap>
<select id="selectDbTableColumnsByName" parameterType="String" resultMap="GenTableColumnResult"> <select id="selectDbTableColumnsByName" parameterType="String" resultMap="GenTableColumnResult">

@ -4,53 +4,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dromara.gen.mapper.GenTableMapper"> <mapper namespace="org.dromara.gen.mapper.GenTableMapper">
<resultMap type="GenTable" id="GenTableResult"> <!-- 多结构嵌套自动映射需带上每个实体的主键id 否则映射会失败 -->
<resultMap type="org.dromara.gen.domain.GenTable" id="GenTableResult">
<id property="tableId" column="table_id" /> <id property="tableId" column="table_id" />
<result property="tableName" column="table_name" />
<result property="tableComment" column="table_comment" />
<result property="subTableName" column="sub_table_name" />
<result property="subTableFkName" column="sub_table_fk_name" />
<result property="className" column="class_name" />
<result property="tplCategory" column="tpl_category" />
<result property="packageName" column="package_name" />
<result property="moduleName" column="module_name" />
<result property="businessName" column="business_name" />
<result property="functionName" column="function_name" />
<result property="functionAuthor" column="function_author" />
<result property="genType" column="gen_type" />
<result property="genPath" column="gen_path" />
<result property="options" column="options" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
<collection property="columns" javaType="java.util.List" resultMap="GenTableColumnResult" /> <collection property="columns" javaType="java.util.List" resultMap="GenTableColumnResult" />
</resultMap> </resultMap>
<resultMap type="GenTableColumn" id="GenTableColumnResult"> <resultMap type="org.dromara.gen.domain.GenTableColumn" id="GenTableColumnResult">
<id property="columnId" column="column_id"/> <id property="columnId" column="column_id"/>
<result property="tableId" column="table_id" />
<result property="columnName" column="column_name" />
<result property="columnComment" column="column_comment" />
<result property="columnType" column="column_type" />
<result property="javaType" column="java_type" />
<result property="javaField" column="java_field" />
<result property="isPk" column="is_pk" />
<result property="isIncrement" column="is_increment" />
<result property="isRequired" column="is_required" />
<result property="isInsert" column="is_insert" />
<result property="isEdit" column="is_edit" />
<result property="isList" column="is_list" />
<result property="isQuery" column="is_query" />
<result property="queryType" column="query_type" />
<result property="htmlType" column="html_type" />
<result property="dictType" column="dict_type" />
<result property="sort" column="sort" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap> </resultMap>
<select id="selectPageDbTableList" resultMap="GenTableResult"> <select id="selectPageDbTableList" resultMap="GenTableResult">
@ -59,7 +20,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
from information_schema.tables from information_schema.tables
where table_schema = (select database()) where table_schema = (select database())
AND table_name NOT LIKE 'xxl_job_%' AND table_name NOT LIKE 'gen_%' AND table_name NOT LIKE 'xxl_job_%' AND table_name NOT LIKE 'gen_%'
AND table_name NOT IN (select table_name from gen_table) <if test="genTable.params.genTableNames != null and genTable.params.genTableNames.size > 0">
AND table_name NOT IN
<foreach collection="genTable.params.genTableNames" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
<if test="genTable.tableName != null and genTable.tableName != ''"> <if test="genTable.tableName != null and genTable.tableName != ''">
AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%')) AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%'))
</if> </if>
@ -75,7 +41,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and dt.table_name = uo.object_name and dt.table_name = uo.object_name
and uo.object_type = 'TABLE' and uo.object_type = 'TABLE'
AND dt.table_name NOT LIKE 'XXL_JOB_%' AND dt.table_name NOT LIKE 'GEN_%' AND dt.table_name NOT LIKE 'XXL_JOB_%' AND dt.table_name NOT LIKE 'GEN_%'
AND lower(dt.table_name) NOT IN (select table_name from gen_table) <if test="genTable.params.genTableNames != null and genTable.params.genTableNames.size > 0">
AND lower(dt.table_name) NOT IN
<foreach collection="genTable.params.genTableNames" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
<if test="genTable.tableName != null and genTable.tableName != ''"> <if test="genTable.tableName != null and genTable.tableName != ''">
AND lower(dt.table_name) like lower(concat(concat('%', #{genTable.tableName}), '%')) AND lower(dt.table_name) like lower(concat(concat('%', #{genTable.tableName}), '%'))
</if> </if>
@ -99,7 +70,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
AND n.nspname <![CDATA[ <> ]]> ''::name AND n.nspname <![CDATA[ <> ]]> ''::name
) list_table ) list_table
where table_name NOT LIKE 'xxl_job_%' AND table_name NOT LIKE 'gen_%' where table_name NOT LIKE 'xxl_job_%' AND table_name NOT LIKE 'gen_%'
AND table_name NOT IN (select table_name from gen_table) <if test="genTable.params.genTableNames != null and genTable.params.genTableNames.size > 0">
AND table_name NOT IN
<foreach collection="genTable.params.genTableNames" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
<if test="genTable.tableName != null and genTable.tableName != ''"> <if test="genTable.tableName != null and genTable.tableName != ''">
AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%')) AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%'))
</if> </if>
@ -126,7 +102,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and dt.table_name = uo.object_name and dt.table_name = uo.object_name
and uo.object_type = 'TABLE' and uo.object_type = 'TABLE'
AND dt.table_name NOT LIKE 'XXL_JOB_%' AND dt.table_name NOT LIKE 'GEN_%' AND dt.table_name NOT LIKE 'XXL_JOB_%' AND dt.table_name NOT LIKE 'GEN_%'
AND dt.table_name NOT IN (select table_name from gen_table)
and lower(dt.table_name) in and lower(dt.table_name) in
<foreach collection="array" item="name" open="(" separator="," close=")"> <foreach collection="array" item="name" open="(" separator="," close=")">
#{name} #{name}
@ -190,7 +165,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select> </select>
<select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult"> <select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, 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, SELECT t.table_id, t.data_name, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, 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 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 FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id LEFT JOIN gen_table_column c ON t.table_id = c.table_id
@ -198,7 +173,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select> </select>
<select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult"> <select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, 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, SELECT t.table_id, t.data_name, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, 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 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 FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id LEFT JOIN gen_table_column c ON t.table_id = c.table_id
@ -206,11 +181,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select> </select>
<select id="selectGenTableAll" parameterType="String" resultMap="GenTableResult"> <select id="selectGenTableAll" parameterType="String" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.options, t.remark, SELECT t.table_id, t.data_name, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, 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 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 FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id LEFT JOIN gen_table_column c ON t.table_id = c.table_id
order by c.sort order by c.sort
</select> </select>
<select id="selectTableNameList" resultType="java.lang.String">
select table_name from gen_table where data_name = #{dataName,jdbcType=VARCHAR}
</select>
</mapper> </mapper>

Loading…
Cancel
Save