This commit is contained in:
dute7liang
2023-12-19 22:25:27 +08:00
parent 5676aa7fde
commit 5b04a92a55
385 changed files with 31644 additions and 0 deletions

View File

@@ -0,0 +1,73 @@
package com.bashi.generator.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* 读取代码生成相关配置
*
* @author duteliang
*/
@Component
@ConfigurationProperties(prefix = "gen")
@PropertySource(value = { "classpath:generator.yml" })
public class GenConfig
{
/** 作者 */
public static String author;
/** 生成包路径 */
public static String packageName;
/** 自动去除表前缀默认是false */
public static boolean autoRemovePre;
/** 表前缀(类名不会包含表前缀) */
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

@@ -0,0 +1,204 @@
package com.bashi.generator.controller;
import cn.hutool.core.convert.Convert;
import com.bashi.common.annotation.Log;
import com.bashi.common.core.controller.BaseController;
import com.bashi.common.core.domain.AjaxResult;
import com.bashi.common.core.page.TableDataInfo;
import com.bashi.common.enums.BusinessType;
import com.bashi.generator.domain.GenTable;
import com.bashi.generator.domain.GenTableColumn;
import com.bashi.generator.service.IGenTableColumnService;
import com.bashi.generator.service.IGenTableService;
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.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 代码生成 操作处理
*
* @author duteliang
*/
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController
{
@Autowired
private IGenTableService genTableService;
@Autowired
private IGenTableColumnService genTableColumnService;
/**
* 查询代码生成列表
*/
@PreAuthorize("@ss.hasPermi('tool:gen:list')")
@GetMapping("/list")
public TableDataInfo genList(GenTable genTable)
{
return genTableService.selectPageGenTableList(genTable);
}
/**
* 修改代码生成业务
*/
@PreAuthorize("@ss.hasPermi('tool:gen:query')")
@GetMapping(value = "/{talbleId}")
public AjaxResult getInfo(@PathVariable Long talbleId)
{
GenTable table = genTableService.selectGenTableById(talbleId);
List<GenTable> tables = genTableService.selectGenTableAll();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
Map<String, Object> map = new HashMap<String, Object>();
map.put("info", table);
map.put("rows", list);
map.put("tables", tables);
return AjaxResult.success(map);
}
/**
* 查询数据库列表
*/
@PreAuthorize("@ss.hasPermi('tool:gen:list')")
@GetMapping("/db/list")
public TableDataInfo dataList(GenTable genTable)
{
return genTableService.selectPageDbTableList(genTable);
}
/**
* 查询数据表字段列表
*/
@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:import')")
@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:edit')")
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult editSave(@Validated @RequestBody GenTable genTable)
{
genTableService.validateEdit(genTable);
genTableService.updateGenTable(genTable);
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:preview')")
@GetMapping("/preview/{tableId}")
public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException
{
Map<String, String> dataMap = genTableService.previewCode(tableId);
return AjaxResult.success(dataMap);
}
/**
* 生成代码(下载方式)
*/
@PreAuthorize("@ss.hasPermi('tool:gen:code')")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/download/{tableName}")
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
{
byte[] data = genTableService.downloadCode(tableName);
genCode(response, data);
}
/**
* 生成代码(自定义路径)
*/
@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();
}
/**
* 批量生成代码
*/
@PreAuthorize("@ss.hasPermi('tool:gen:code')")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/batchGenCode")
public void batchGenCode(HttpServletResponse response, String tables) throws IOException
{
String[] tableNames = Convert.toStrArray(tables);
byte[] data = genTableService.downloadCode(tableNames);
genCode(response, data);
}
/**
* 生成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=\"caocao.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
}
}

View File

@@ -0,0 +1,237 @@
package com.bashi.generator.domain;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.bashi.common.constant.GenConstants;
import lombok.*;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.ArrayUtils;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 业务表 gen_table
*
* @author duteliang
*/
@Data
@NoArgsConstructor
@Accessors(chain = true)
@TableName("gen_table")
public class GenTable implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 编号
*/
@TableId(value = "table_id", type = IdType.AUTO)
private Long tableId;
/**
* 表名称
*/
@NotBlank(message = "表名称不能为空")
private String tableName;
/**
* 表描述
*/
@NotBlank(message = "表描述不能为空")
private String tableComment;
/**
* 关联父表的表名
*/
private String subTableName;
/**
* 本表关联父表的外键名
*/
private String subTableFkName;
/**
* 实体类名称(首字母大写)
*/
@NotBlank(message = "实体类名称不能为空")
private String className;
/**
* 使用的模板crud单表操作 tree树表操作 sub主子表操作
*/
private String tplCategory;
/**
* 生成包路径
*/
@NotBlank(message = "生成包路径不能为空")
private String packageName;
/**
* 生成模块名
*/
@NotBlank(message = "生成模块名不能为空")
private String moduleName;
/**
* 生成业务名
*/
@NotBlank(message = "生成业务名不能为空")
private String businessName;
/**
* 生成功能名
*/
@NotBlank(message = "生成功能名不能为空")
private String functionName;
/**
* 生成作者
*/
@NotBlank(message = "作者不能为空")
private String functionAuthor;
/**
* 生成代码方式0zip压缩包 1自定义路径
*/
private String genType;
/**
* 生成路径(不填默认项目路径)
*/
private String genPath;
/**
* 主键信息
*/
@TableField(exist = false)
private GenTableColumn pkColumn;
/**
* 子表信息
*/
@TableField(exist = false)
private GenTable subTable;
/**
* 表列信息
*/
@Valid
@TableField(exist = false)
private List<GenTableColumn> columns;
/**
* 其它生成选项
*/
private String options;
/**
* 创建者
*/
@TableField(fill = FieldFill.INSERT)
private String createBy;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 更新者
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**
* 备注
*/
private String remark;
/**
* 请求参数
*/
@TableField(exist = false)
private Map<String, Object> params = new HashMap<>();
/**
* 树编码字段
*/
@TableField(exist = false)
private String treeCode;
/**
* 树父编码字段
*/
@TableField(exist = false)
private String treeParentCode;
/**
* 树名称字段
*/
@TableField(exist = false)
private String treeName;
/**
* 上级菜单ID字段
*/
@TableField(exist = false)
private String parentMenuId;
/**
* 上级菜单名称字段
*/
@TableField(exist = false)
private String parentMenuName;
public boolean isSub() {
return isSub(this.tplCategory);
}
public static boolean isSub(String tplCategory) {
return tplCategory != null && StrUtil.equals(GenConstants.TPL_SUB, tplCategory);
}
public boolean isTree() {
return isTree(this.tplCategory);
}
public static boolean isTree(String tplCategory) {
return tplCategory != null && StrUtil.equals(GenConstants.TPL_TREE, tplCategory);
}
public boolean isCrud() {
return isCrud(this.tplCategory);
}
public static boolean isCrud(String tplCategory) {
return tplCategory != null && StrUtil.equals(GenConstants.TPL_CRUD, tplCategory);
}
public boolean isSuperColumn(String javaField) {
return isSuperColumn(this.tplCategory, javaField);
}
public static boolean isSuperColumn(String tplCategory, String javaField) {
if (isTree(tplCategory)) {
return StrUtil.equalsAnyIgnoreCase(javaField,
ArrayUtils.addAll(GenConstants.TREE_ENTITY, GenConstants.BASE_ENTITY));
}
return StrUtil.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY);
}
}

View File

@@ -0,0 +1,249 @@
package com.bashi.generator.domain;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 代码生成业务字段表 gen_table_column
*
* @author duteliang
*/
@Data
@NoArgsConstructor
@Accessors(chain = true)
@TableName("gen_table_column")
public class GenTableColumn implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 编号
*/
@TableId(value = "column_id", type = IdType.AUTO)
private Long columnId;
/**
* 归属表编号
*/
private Long tableId;
/**
* 列名称
*/
private String columnName;
/**
* 列描述
*/
private String columnComment;
/**
* 列类型
*/
private String columnType;
/**
* JAVA类型
*/
private String javaType;
/**
* JAVA字段名
*/
@NotBlank(message = "Java属性不能为空")
private String javaField;
/**
* 是否主键1是
*/
private String isPk;
/**
* 是否自增1是
*/
private String isIncrement;
/**
* 是否必填1是
*/
private String isRequired;
/**
* 是否为插入字段1是
*/
private String isInsert;
/**
* 是否编辑字段1是
*/
private String isEdit;
/**
* 是否列表字段1是
*/
private String isList;
/**
* 是否查询字段1是
*/
private String isQuery;
/**
* 查询方式EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围
*/
private String queryType;
/**
* 显示类型input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、image图片上传控件、upload文件上传控件、editor富文本控件
*/
private String htmlType;
/**
* 字典类型
*/
private String dictType;
/**
* 排序
*/
private Integer sort;
/**
* 创建者
*/
@TableField(fill = FieldFill.INSERT)
private String createBy;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 更新者
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**
* 请求参数
*/
@TableField(exist = false)
private Map<String, Object> params = new HashMap<>();
public String getCapJavaField() {
return StrUtil.upperFirst(javaField);
}
public boolean isPk() {
return isPk(this.isPk);
}
public boolean isPk(String isPk) {
return isPk != null && StrUtil.equals("1", isPk);
}
public boolean isIncrement() {
return isIncrement(this.isIncrement);
}
public boolean isIncrement(String isIncrement) {
return isIncrement != null && StrUtil.equals("1", isIncrement);
}
public boolean isRequired() {
return isRequired(this.isRequired);
}
public boolean isRequired(String isRequired) {
return isRequired != null && StrUtil.equals("1", isRequired);
}
public boolean isInsert() {
return isInsert(this.isInsert);
}
public boolean isInsert(String isInsert) {
return isInsert != null && StrUtil.equals("1", isInsert);
}
public boolean isEdit() {
return isInsert(this.isEdit);
}
public boolean isEdit(String isEdit) {
return isEdit != null && StrUtil.equals("1", isEdit);
}
public boolean isList() {
return isList(this.isList);
}
public boolean isList(String isList) {
return isList != null && StrUtil.equals("1", isList);
}
public boolean isQuery() {
return isQuery(this.isQuery);
}
public boolean isQuery(String isQuery) {
return isQuery != null && StrUtil.equals("1", isQuery);
}
public boolean isSuperColumn() {
return isSuperColumn(this.javaField);
}
public static boolean isSuperColumn(String javaField) {
return StrUtil.equalsAnyIgnoreCase(javaField,
// BaseEntity
"createBy", "createTime", "updateBy", "updateTime", "remark",
// TreeEntity
"parentName", "parentId", "orderNum", "ancestors");
}
public boolean isUsableColumn() {
return isUsableColumn(javaField);
}
public static boolean isUsableColumn(String javaField) {
// isSuperColumn()中的名单用于避免生成多余Domain属性若某些属性在生成页面时需要用到不能忽略则放在此处白名单
return StrUtil.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark");
}
public String readConverterExp() {
String remarks = StrUtil.subBetween(this.columnComment, "", "");
StringBuffer sb = new StringBuffer();
if (StrUtil.isNotEmpty(remarks)) {
for (String value : remarks.split(" ")) {
if (StrUtil.isNotEmpty(value)) {
Object startStr = value.subSequence(0, 1);
String endStr = value.substring(1);
sb.append("").append(startStr).append("=").append(endStr).append(",");
}
}
return sb.deleteCharAt(sb.length() - 1).toString();
} else {
return this.columnComment;
}
}
}

View File

@@ -0,0 +1,22 @@
package com.bashi.generator.mapper;
import com.bashi.common.core.mybatisplus.core.BaseMapperPlus;
import com.bashi.generator.domain.GenTableColumn;
import java.util.List;
/**
* 业务字段 数据层
*
* @author duteliang
*/
public interface GenTableColumnMapper extends BaseMapperPlus<GenTableColumn> {
/**
* 根据表名称查询列信息
*
* @param tableName 表名称
* @return 列信息
*/
public List<GenTableColumn> selectDbTableColumnsByName(String tableName);
}

View File

@@ -0,0 +1,69 @@
package com.bashi.generator.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bashi.common.core.mybatisplus.core.BaseMapperPlus;
import com.bashi.generator.domain.GenTable;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 业务 数据层
*
* @author duteliang
*/
public interface GenTableMapper extends BaseMapperPlus<GenTable> {
Page<GenTable> selectPageGenTableList(@Param("page") Page<GenTable> page, @Param("genTable") GenTable genTable);
Page<GenTable> selectPageDbTableList(@Param("page") Page<GenTable> page, @Param("genTable") GenTable genTable);
/**
* 查询业务列表
*
* @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);
/**
* 查询所有表信息
*
* @return 表信息集合
*/
public List<GenTable> selectGenTableAll();
/**
* 查询表ID业务信息
*
* @param id 业务ID
* @return 业务信息
*/
public GenTable selectGenTableById(Long id);
/**
* 查询表名称业务信息
*
* @param tableName 表名称
* @return 业务信息
*/
public GenTable selectGenTableByName(String tableName);
}

View File

@@ -0,0 +1,65 @@
package com.bashi.generator.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bashi.generator.domain.GenTableColumn;
import com.bashi.generator.mapper.GenTableColumnMapper;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
/**
* 业务字段 服务层实现
*
* @author duteliang
*/
@Service
public class GenTableColumnServiceImpl extends ServiceImpl<GenTableColumnMapper, GenTableColumn> implements IGenTableColumnService {
/**
* 查询业务字段列表
*
* @param tableId 业务字段编号
* @return 业务字段集合
*/
@Override
public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) {
return list(new LambdaQueryWrapper<GenTableColumn>()
.eq(GenTableColumn::getTableId,tableId)
.orderByAsc(GenTableColumn::getSort));
}
/**
* 新增业务字段
*
* @param genTableColumn 业务字段信息
* @return 结果
*/
@Override
public int insertGenTableColumn(GenTableColumn genTableColumn) {
return baseMapper.insert(genTableColumn);
}
/**
* 修改业务字段
*
* @param genTableColumn 业务字段信息
* @return 结果
*/
@Override
public int updateGenTableColumn(GenTableColumn genTableColumn) {
return baseMapper.updateById(genTableColumn);
}
/**
* 删除业务字段对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteGenTableColumnByIds(String ids) {
return baseMapper.deleteBatchIds(Arrays.asList(ids.split(",")));
}
}

View File

@@ -0,0 +1,457 @@
package com.bashi.generator.service;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bashi.common.constant.Constants;
import com.bashi.common.constant.GenConstants;
import com.bashi.common.core.page.TableDataInfo;
import com.bashi.common.exception.CustomException;
import com.bashi.common.utils.JsonUtils;
import com.bashi.common.utils.PageUtils;
import com.bashi.common.utils.SecurityUtils;
import com.bashi.common.utils.file.FileUtils;
import com.bashi.generator.domain.GenTable;
import com.bashi.generator.domain.GenTableColumn;
import com.bashi.generator.mapper.GenTableColumnMapper;
import com.bashi.generator.mapper.GenTableMapper;
import com.bashi.generator.util.GenUtils;
import com.bashi.generator.util.VelocityInitializer;
import com.bashi.generator.util.VelocityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
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;
/**
* 业务 服务层实现
*
* @author duteliang
*/
@Slf4j
@Service
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements IGenTableService {
@Autowired
private GenTableColumnMapper genTableColumnMapper;
/**
* 查询业务信息
*
* @param id 业务ID
* @return 业务信息
*/
@Override
public GenTable selectGenTableById(Long id) {
GenTable genTable = baseMapper.selectGenTableById(id);
setTableFromOptions(genTable);
return genTable;
}
@Override
public TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable) {
return PageUtils.buildDataInfo(baseMapper.selectPageGenTableList(PageUtils.buildPage(), genTable));
}
@Override
public TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable) {
return PageUtils.buildDataInfo(baseMapper.selectPageDbTableList(PageUtils.buildPage(), genTable));
}
/**
* 查询业务列表
*
* @param genTable 业务信息
* @return 业务集合
*/
@Override
public List<GenTable> selectGenTableList(GenTable genTable) {
return baseMapper.selectGenTableList(genTable);
}
/**
* 查询据库列表
*
* @param genTable 业务信息
* @return 数据库表集合
*/
@Override
public List<GenTable> selectDbTableList(GenTable genTable) {
return baseMapper.selectDbTableList(genTable);
}
/**
* 查询据库列表
*
* @param tableNames 表名称组
* @return 数据库表集合
*/
@Override
public List<GenTable> selectDbTableListByNames(String[] tableNames) {
return baseMapper.selectDbTableListByNames(tableNames);
}
/**
* 查询所有表信息
*
* @return 表信息集合
*/
@Override
public List<GenTable> selectGenTableAll() {
return baseMapper.selectGenTableAll();
}
/**
* 修改业务
*
* @param genTable 业务信息
* @return 结果
*/
@Override
@Transactional
public void updateGenTable(GenTable genTable) {
String options = JsonUtils.toJsonString(genTable.getParams());
genTable.setOptions(options);
int row = baseMapper.updateById(genTable);
if (row > 0) {
for (GenTableColumn cenTableColumn : genTable.getColumns()) {
genTableColumnMapper.update(cenTableColumn,
new LambdaUpdateWrapper<GenTableColumn>()
.set(cenTableColumn.getIsPk() == null, GenTableColumn::getIsPk, null)
.set(cenTableColumn.getIsIncrement() == null, GenTableColumn::getIsIncrement, null)
.set(cenTableColumn.getIsInsert() == null, GenTableColumn::getIsInsert, null)
.set(cenTableColumn.getIsEdit() == null, GenTableColumn::getIsEdit, null)
.set(cenTableColumn.getIsList() == null, GenTableColumn::getIsList, null)
.set(cenTableColumn.getIsQuery() == null, GenTableColumn::getIsQuery, null)
.set(cenTableColumn.getIsRequired() == null, GenTableColumn::getIsRequired, null)
.eq(GenTableColumn::getColumnId,cenTableColumn.getColumnId()));
}
}
}
/**
* 删除业务对象
*
* @param tableIds 需要删除的数据ID
* @return 结果
*/
@Override
@Transactional
public void deleteGenTableByIds(Long[] tableIds) {
List<Long> ids = Arrays.asList(tableIds);
removeByIds(ids);
genTableColumnMapper.delete(new LambdaQueryWrapper<GenTableColumn>().in(GenTableColumn::getTableId, ids));
}
/**
* 导入表结构
*
* @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 = baseMapper.insert(table);
if (row > 0) {
// 保存列信息
List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
for (GenTableColumn column : genTableColumns) {
GenUtils.initColumnField(column, table);
genTableColumnMapper.insert(column);
}
}
}
} catch (Exception e) {
throw new CustomException("导入失败:" + e.getMessage());
}
}
/**
* 预览代码
*
* @param tableId 表编号
* @return 预览数据列表
*/
@Override
public Map<String, String> previewCode(Long tableId) {
Map<String, String> dataMap = new LinkedHashMap<>();
// 查询表信息
GenTable table = baseMapper.selectGenTableById(tableId);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
dataMap.put(template, sw.toString());
}
return dataMap;
}
/**
* 生成代码(下载方式)
*
* @param tableName 表名称
* @return 数据
*/
@Override
public byte[] downloadCode(String tableName) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
generatorCode(tableName, zip);
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 生成代码(自定义路径)
*
* @param tableName 表名称
*/
@Override
public void generatorCode(String tableName) {
// 查询表信息
GenTable table = baseMapper.selectGenTableByName(tableName);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
if (!StrUtil.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
String path = getGenPath(table, template);
FileUtils.writeUtf8String(sw.toString(), path);
}
}
}
/**
* 同步数据库
*
* @param tableName 表名称
*/
@Override
@Transactional
public void synchDb(String tableName) {
GenTable table = baseMapper.selectGenTableByName(tableName);
List<GenTableColumn> tableColumns = table.getColumns();
List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
if (Validator.isEmpty(dbTableColumns)) {
throw new CustomException("同步数据失败,原表结构不存在");
}
List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
dbTableColumns.forEach(column -> {
if (!tableColumnNames.contains(column.getColumnName())) {
GenUtils.initColumnField(column, table);
genTableColumnMapper.insert(column);
}
});
List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(delColumns)) {
List<Long> ids = delColumns.stream().map(GenTableColumn::getColumnId).collect(Collectors.toList());
genTableColumnMapper.deleteBatchIds(ids);
}
}
/**
* 批量生成代码(下载方式)
*
* @param tableNames 表数组
* @return 数据
*/
@Override
public byte[] downloadCode(String[] tableNames) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) {
generatorCode(tableName, zip);
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 查询表信息并生成代码
*/
private void generatorCode(String tableName, ZipOutputStream zip) {
// 查询表信息
GenTable table = baseMapper.selectGenTableByName(tableName);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
try {
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
IOUtils.write(sw.toString(), zip, Constants.UTF8);
IOUtils.closeQuietly(sw);
zip.flush();
zip.closeEntry();
} catch (IOException e) {
log.error("渲染模板失败,表名:" + table.getTableName(), e);
}
}
}
/**
* 修改保存参数校验
*
* @param genTable 业务信息
*/
@Override
public void validateEdit(GenTable genTable) {
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
Map<String, Object> paramsObj = genTable.getParams();
if (Validator.isEmpty(paramsObj.get(GenConstants.TREE_CODE))) {
throw new CustomException("树编码字段不能为空");
} else if (Validator.isEmpty(paramsObj.get(GenConstants.TREE_PARENT_CODE))) {
throw new CustomException("树父编码字段不能为空");
} else if (Validator.isEmpty(paramsObj.get(GenConstants.TREE_NAME))) {
throw new CustomException("树名称字段不能为空");
} else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) {
if (Validator.isEmpty(genTable.getSubTableName())) {
throw new CustomException("关联子表的表名不能为空");
} else if (Validator.isEmpty(genTable.getSubTableFkName())) {
throw new CustomException("子表关联的外键名不能为空");
}
}
}
}
/**
* 设置主键列信息
*
* @param table 业务表信息
*/
public void setPkColumn(GenTable table) {
for (GenTableColumn column : table.getColumns()) {
if (column.isPk()) {
table.setPkColumn(column);
break;
}
}
if (Validator.isNull(table.getPkColumn())) {
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 (Validator.isNull(table.getSubTable().getPkColumn())) {
table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
}
}
}
/**
* 设置主子表信息
*
* @param table 业务表信息
*/
public void setSubTable(GenTable table) {
String subTableName = table.getSubTableName();
if (Validator.isNotEmpty(subTableName)) {
table.setSubTable(baseMapper.selectGenTableByName(subTableName));
}
}
/**
* 设置代码生成其他选项值
*
* @param genTable 设置后的生成对象
*/
public void setTableFromOptions(GenTable genTable) {
Map<String, Object> paramsObj = JsonUtils.parseMap(genTable.getOptions());
if (Validator.isNotNull(paramsObj)) {
String treeCode = Convert.toStr(paramsObj.get(GenConstants.TREE_CODE));
String treeParentCode = Convert.toStr(paramsObj.get(GenConstants.TREE_PARENT_CODE));
String treeName = Convert.toStr(paramsObj.get(GenConstants.TREE_NAME));
String parentMenuId = Convert.toStr(paramsObj.get(GenConstants.PARENT_MENU_ID));
String parentMenuName = Convert.toStr(paramsObj.get(GenConstants.PARENT_MENU_NAME));
genTable.setTreeCode(treeCode);
genTable.setTreeParentCode(treeParentCode);
genTable.setTreeName(treeName);
genTable.setParentMenuId(parentMenuId);
genTable.setParentMenuName(parentMenuName);
}
}
/**
* 获取代码生成地址
*
* @param table 业务表信息
* @param template 模板文件路径
* @return 生成地址
*/
public static String getGenPath(GenTable table, String template) {
String genPath = table.getGenPath();
if (StrUtil.equals(genPath, "/")) {
return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
}
return genPath + File.separator + VelocityUtils.getFileName(template, table);
}
}

View File

@@ -0,0 +1,45 @@
package com.bashi.generator.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bashi.generator.domain.GenTableColumn;
import java.util.List;
/**
* 业务字段 服务层
*
* @author duteliang
*/
public interface IGenTableColumnService extends IService<GenTableColumn> {
/**
* 查询业务字段列表
*
* @param tableId 业务字段编号
* @return 业务字段集合
*/
public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId);
/**
* 新增业务字段
*
* @param genTableColumn 业务字段信息
* @return 结果
*/
public int insertGenTableColumn(GenTableColumn genTableColumn);
/**
* 修改业务字段
*
* @param genTableColumn 业务字段信息
* @return 结果
*/
public int updateGenTableColumn(GenTableColumn genTableColumn);
/**
* 删除业务字段信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteGenTableColumnByIds(String ids);
}

View File

@@ -0,0 +1,130 @@
package com.bashi.generator.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bashi.common.core.page.TableDataInfo;
import com.bashi.generator.domain.GenTable;
import java.util.List;
import java.util.Map;
/**
* 业务 服务层
*
* @author duteliang
*/
public interface IGenTableService extends IService<GenTable> {
TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable);
TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable);
/**
* 查询业务列表
*
* @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);
/**
* 查询所有表信息
*
* @return 表信息集合
*/
public List<GenTable> selectGenTableAll();
/**
* 查询业务信息
*
* @param id 业务ID
* @return 业务信息
*/
public GenTable selectGenTableById(Long id);
/**
* 修改业务
*
* @param genTable 业务信息
* @return 结果
*/
public void updateGenTable(GenTable genTable);
/**
* 删除业务信息
*
* @param tableIds 需要删除的表数据ID
* @return 结果
*/
public void deleteGenTableByIds(Long[] tableIds);
/**
* 导入表结构
*
* @param tableList 导入表列表
*/
public void importGenTable(List<GenTable> tableList);
/**
* 预览代码
*
* @param tableId 表编号
* @return 预览数据列表
*/
public Map<String, String> previewCode(Long tableId);
/**
* 生成代码(下载方式)
*
* @param tableName 表名称
* @return 数据
*/
public byte[] downloadCode(String tableName);
/**
* 生成代码(自定义路径)
*
* @param tableName 表名称
* @return 数据
*/
public void generatorCode(String tableName);
/**
* 同步数据库
*
* @param tableName 表名称
*/
public void synchDb(String tableName);
/**
* 批量生成代码(下载方式)
*
* @param tableNames 表数组
* @return 数据
*/
public byte[] downloadCode(String[] tableNames);
/**
* 修改保存参数校验
*
* @param genTable 业务信息
*/
public void validateEdit(GenTable genTable);
}

View File

@@ -0,0 +1,259 @@
package com.bashi.generator.util;
import cn.hutool.core.util.StrUtil;
import com.bashi.common.constant.GenConstants;
import com.bashi.generator.config.GenConfig;
import com.bashi.generator.domain.GenTable;
import com.bashi.generator.domain.GenTableColumn;
import org.apache.commons.lang3.RegExUtils;
import java.util.Arrays;
/**
* 代码生成器 工具类
*
* @author duteliang
*/
public class GenUtils
{
/**
* 初始化表信息
*/
public static void initTable(GenTable genTable, String operName)
{
genTable.setClassName(convertClassName(genTable.getTableName()));
genTable.setPackageName(GenConfig.getPackageName());
genTable.setModuleName(getModuleName(GenConfig.getPackageName()));
genTable.setBusinessName(getBusinessName(genTable.getTableName()));
genTable.setFunctionName(replaceText(genTable.getTableComment()));
genTable.setFunctionAuthor(GenConfig.getAuthor());
genTable.setCreateBy(operName);
}
/**
* 初始化列属性字段
*/
public static void initColumnField(GenTableColumn column, GenTable table)
{
String dataType = getDbType(column.getColumnType());
String columnName = column.getColumnName();
column.setTableId(table.getTableId());
column.setCreateBy(table.getCreateBy());
// 设置java字段名
column.setJavaField(StrUtil.toCamelCase(columnName));
// 设置默认类型
column.setJavaType(GenConstants.TYPE_STRING);
if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType) || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType))
{
// 字符串长度超过500设置为文本域
Integer columnLength = getColumnLength(column.getColumnType());
String htmlType = columnLength >= 500 || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType) ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT;
column.setHtmlType(htmlType);
}
else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType))
{
column.setJavaType(GenConstants.TYPE_DATE);
column.setHtmlType(GenConstants.HTML_DATETIME);
}
else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType))
{
column.setHtmlType(GenConstants.HTML_INPUT);
// 如果是浮点型 统一用BigDecimal
String[] str = StrUtil.splitToArray(StrUtil.subBetween(column.getColumnType(), "(", ")"), ",");
if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0)
{
column.setJavaType(GenConstants.TYPE_BIGDECIMAL);
}
// 如果是整形
else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10)
{
column.setJavaType(GenConstants.TYPE_INTEGER);
}
// 长整形
else
{
column.setJavaType(GenConstants.TYPE_LONG);
}
}
// 插入字段(默认所有字段都需要插入)
column.setIsInsert(GenConstants.REQUIRE);
// 编辑字段
if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName) && !column.isPk())
{
column.setIsEdit(GenConstants.REQUIRE);
}
// 列表字段
if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName) && !column.isPk())
{
column.setIsList(GenConstants.REQUIRE);
}
// 查询字段
if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk())
{
column.setIsQuery(GenConstants.REQUIRE);
}
// 查询字段类型
if (StrUtil.endWithIgnoreCase(columnName, "name"))
{
column.setQueryType(GenConstants.QUERY_LIKE);
}
// 状态字段设置单选框
if (StrUtil.endWithIgnoreCase(columnName, "status"))
{
column.setHtmlType(GenConstants.HTML_RADIO);
}
// 类型&性别字段设置下拉框
else if (StrUtil.endWithIgnoreCase(columnName, "type")
|| StrUtil.endWithIgnoreCase(columnName, "sex"))
{
column.setHtmlType(GenConstants.HTML_SELECT);
}
// 图片字段设置图片上传控件
else if (StrUtil.endWithIgnoreCase(columnName, "image"))
{
column.setHtmlType(GenConstants.HTML_IMAGE_UPLOAD);
}
// 文件字段设置文件上传控件
else if (StrUtil.endWithIgnoreCase(columnName, "file"))
{
column.setHtmlType(GenConstants.HTML_FILE_UPLOAD);
}
// 内容字段设置富文本控件
else if (StrUtil.endWithIgnoreCase(columnName, "content"))
{
column.setHtmlType(GenConstants.HTML_EDITOR);
}
}
/**
* 校验数组是否包含指定值
*
* @param arr 数组
* @param targetValue 值
* @return 是否包含
*/
public static boolean arraysContains(String[] arr, String targetValue)
{
return Arrays.asList(arr).contains(targetValue);
}
/**
* 获取模块名
*
* @param packageName 包名
* @return 模块名
*/
public static String getModuleName(String packageName)
{
int lastIndex = packageName.lastIndexOf(".");
int nameLength = packageName.length();
String moduleName = StrUtil.sub(packageName, lastIndex + 1, nameLength);
return moduleName;
}
/**
* 获取业务名
*
* @param tableName 表名
* @return 业务名
*/
public static String getBusinessName(String tableName)
{
int lastIndex = tableName.lastIndexOf("_");
int nameLength = tableName.length();
String businessName = StrUtil.sub(tableName, lastIndex + 1, nameLength);
return businessName;
}
/**
* 表名转换成Java类名
*
* @param tableName 表名称
* @return 类名
*/
public static String convertClassName(String tableName)
{
boolean autoRemovePre = GenConfig.getAutoRemovePre();
String tablePrefix = GenConfig.getTablePrefix();
if (autoRemovePre && StrUtil.isNotEmpty(tablePrefix))
{
String[] searchList = StrUtil.splitToArray(tablePrefix, ",");
tableName = replaceFirst(tableName, searchList);
}
return StrUtil.upperFirst(StrUtil.toCamelCase(tableName));
}
/**
* 批量替换前缀
*
* @param replacementm 替换值
* @param searchList 替换列表
* @return
*/
public static String replaceFirst(String replacementm, String[] searchList)
{
String text = replacementm;
for (String searchString : searchList)
{
if (replacementm.startsWith(searchString))
{
text = replacementm.replaceFirst(searchString, "");
break;
}
}
return text;
}
/**
* 关键字替换
*
* @param text 需要被替换的名字
* @return 替换后的名字
*/
public static String replaceText(String text)
{
return RegExUtils.replaceAll(text, "(?:表|若依)", "");
}
/**
* 获取数据库类型字段
*
* @param columnType 列类型
* @return 截取后的列类型
*/
public static String getDbType(String columnType)
{
if (StrUtil.indexOf(columnType, '(') > 0)
{
return StrUtil.subBefore(columnType, "(",false);
}
else
{
return columnType;
}
}
/**
* 获取字段长度
*
* @param columnType 列类型
* @return 截取后的列类型
*/
public static Integer getColumnLength(String columnType)
{
if (StrUtil.indexOf(columnType, '(') > 0)
{
String length = StrUtil.subBetween(columnType, "(", ")");
return Integer.valueOf(length);
}
else
{
return 0;
}
}
}

View File

@@ -0,0 +1,35 @@
package com.bashi.generator.util;
import java.util.Properties;
import org.apache.velocity.app.Velocity;
import com.bashi.common.constant.Constants;
/**
* VelocityEngine工厂
*
* @author duteliang
*/
public class VelocityInitializer
{
/**
* 初始化vm方法
*/
public static void initVelocity()
{
Properties p = new Properties();
try
{
// 加载classpath目录下的vm文件
p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// 定义字符集
p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8);
p.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8);
// 初始化Velocity引擎指定配置Properties
Velocity.init(p);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,385 @@
package com.bashi.generator.util;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.bashi.common.constant.GenConstants;
import com.bashi.common.utils.DateUtils;
import com.bashi.common.utils.JsonUtils;
import com.bashi.generator.domain.GenTable;
import com.bashi.generator.domain.GenTableColumn;
import org.apache.velocity.VelocityContext;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* 模板处理工具类
*
* @author duteliang
*/
public class VelocityUtils
{
/** 项目空间路径 */
private static final String PROJECT_PATH = "main/java";
/** mybatis空间路径 */
private static final String MYBATIS_PATH = "main/resources/mapper";
/** 默认上级菜单,系统工具 */
private static final String DEFAULT_PARENT_MENU_ID = "3";
/**
* 设置模板变量信息
*
* @return 模板列表
*/
public static VelocityContext prepareContext(GenTable genTable)
{
String moduleName = genTable.getModuleName();
String businessName = genTable.getBusinessName();
String packageName = genTable.getPackageName();
String tplCategory = genTable.getTplCategory();
String functionName = genTable.getFunctionName();
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("tplCategory", genTable.getTplCategory());
velocityContext.put("tableName", genTable.getTableName());
velocityContext.put("functionName", StrUtil.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
velocityContext.put("ClassName", genTable.getClassName());
velocityContext.put("className", StrUtil.lowerFirst(genTable.getClassName()));
velocityContext.put("moduleName", genTable.getModuleName());
velocityContext.put("BusinessName", StrUtil.upperFirst(genTable.getBusinessName()));
velocityContext.put("businessName", genTable.getBusinessName());
velocityContext.put("basePackage", getPackagePrefix(packageName));
velocityContext.put("packageName", packageName);
velocityContext.put("author", genTable.getFunctionAuthor());
velocityContext.put("datetime", DateUtils.getDate());
velocityContext.put("pkColumn", genTable.getPkColumn());
velocityContext.put("importList", getImportList(genTable));
velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
velocityContext.put("columns", genTable.getColumns());
velocityContext.put("table", genTable);
setMenuVelocityContext(velocityContext, genTable);
if (GenConstants.TPL_TREE.equals(tplCategory))
{
setTreeVelocityContext(velocityContext, genTable);
}
if (GenConstants.TPL_SUB.equals(tplCategory))
{
setSubVelocityContext(velocityContext, genTable);
}
return velocityContext;
}
public static void setMenuVelocityContext(VelocityContext context, GenTable genTable)
{
String options = genTable.getOptions();
Map<String, Object> paramsObj = JsonUtils.parseMap(options);
String parentMenuId = getParentMenuId(paramsObj);
context.put("parentMenuId", parentMenuId);
}
public static void setTreeVelocityContext(VelocityContext context, GenTable genTable)
{
String options = genTable.getOptions();
Map<String, Object> paramsObj = JsonUtils.parseMap(options);
String treeCode = getTreecode(paramsObj);
String treeParentCode = getTreeParentCode(paramsObj);
String treeName = getTreeName(paramsObj);
context.put("treeCode", treeCode);
context.put("treeParentCode", treeParentCode);
context.put("treeName", treeName);
context.put("expandColumn", getExpandColumn(genTable));
if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE))
{
context.put("tree_parent_code", paramsObj.get(GenConstants.TREE_PARENT_CODE));
}
if (paramsObj.containsKey(GenConstants.TREE_NAME))
{
context.put("tree_name", paramsObj.get(GenConstants.TREE_NAME));
}
}
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 = StrUtil.toCamelCase(subTableFkName);
context.put("subTable", subTable);
context.put("subTableName", subTableName);
context.put("subTableFkName", subTableFkName);
context.put("subTableFkClassName", subTableFkClassName);
context.put("subTableFkclassName", StrUtil.lowerFirst(subTableFkClassName));
context.put("subClassName", subClassName);
context.put("subclassName", StrUtil.lowerFirst(subClassName));
context.put("subImportList", getImportList(genTable.getSubTable()));
}
/**
* 获取模板信息
*
* @return 模板列表
*/
public static List<String> getTemplateList(String tplCategory)
{
List<String> templates = new ArrayList<String>();
templates.add("vm/java/domain.java.vm");
templates.add("vm/java/vo.java.vm");
templates.add("vm/java/queryBo.java.vm");
templates.add("vm/java/addBo.java.vm");
templates.add("vm/java/editBo.java.vm");
templates.add("vm/java/mapper.java.vm");
templates.add("vm/java/service.java.vm");
templates.add("vm/java/serviceImpl.java.vm");
templates.add("vm/java/controller.java.vm");
templates.add("vm/xml/mapper.xml.vm");
templates.add("vm/sql/sql.vm");
templates.add("vm/js/api.js.vm");
if (GenConstants.TPL_CRUD.equals(tplCategory))
{
templates.add("vm/vue/index.vue.vm");
}
else if (GenConstants.TPL_TREE.equals(tplCategory))
{
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;
}
/**
* 获取文件名
*/
public static String getFileName(String template, GenTable genTable)
{
// 文件名称
String fileName = "";
// 包路径
String packageName = genTable.getPackageName();
// 模块名
String moduleName = genTable.getModuleName();
// 大写类名
String className = genTable.getClassName();
// 业务名称
String businessName = genTable.getBusinessName();
String javaPath = PROJECT_PATH + "/" + StrUtil.replace(packageName, ".", "/");
String mybatisPath = MYBATIS_PATH + "/" + moduleName;
String vuePath = "vue";
if (template.contains("domain.java.vm"))
{
fileName = StrUtil.format("{}/domain/{}.java", javaPath, className);
}
if (template.contains("vo.java.vm"))
{
fileName = StrUtil.format("{}/vo/{}Vo.java", javaPath, className);
}
if (template.contains("queryBo.java.vm"))
{
fileName = StrUtil.format("{}/bo/{}QueryBo.java", javaPath, className);
}
if (template.contains("addBo.java.vm"))
{
fileName = StrUtil.format("{}/bo/{}AddBo.java", javaPath, className);
}
if (template.contains("editBo.java.vm"))
{
fileName = StrUtil.format("{}/bo/{}EditBo.java", javaPath, className);
}
if (template.contains("sub-domain.java.vm") && StrUtil.equals(GenConstants.TPL_SUB, genTable.getTplCategory()))
{
fileName = StrUtil.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName());
}
else if (template.contains("mapper.java.vm"))
{
fileName = StrUtil.format("{}/mapper/{}Mapper.java", javaPath, className);
}
else if (template.contains("service.java.vm"))
{
fileName = StrUtil.format("{}/service/I{}Service.java", javaPath, className);
}
else if (template.contains("serviceImpl.java.vm"))
{
fileName = StrUtil.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
}
else if (template.contains("controller.java.vm"))
{
fileName = StrUtil.format("{}/controller/{}Controller.java", javaPath, className);
}
else if (template.contains("mapper.xml.vm"))
{
fileName = StrUtil.format("{}/{}Mapper.xml", mybatisPath, className);
}
else if (template.contains("sql.vm"))
{
fileName = businessName + "Menu.sql";
}
else if (template.contains("api.js.vm"))
{
fileName = StrUtil.format("{}/api/{}/{}.js", vuePath, moduleName, businessName);
}
else if (template.contains("index.vue.vm"))
{
fileName = StrUtil.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
}
else if (template.contains("index-tree.vue.vm"))
{
fileName = StrUtil.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
}
return fileName;
}
/**
* 获取包前缀
*
* @param packageName 包名称
* @return 包前缀名称
*/
public static String getPackagePrefix(String packageName)
{
int lastIndex = packageName.lastIndexOf(".");
String basePackage = StrUtil.sub(packageName, 0, lastIndex);
return basePackage;
}
/**
* 根据列类型获取导入包
*
* @param genTable 业务表对象
* @return 返回需要导入的包列表
*/
public static HashSet<String> getImportList(GenTable genTable)
{
List<GenTableColumn> columns = genTable.getColumns();
GenTable subGenTable = genTable.getSubTable();
HashSet<String> importList = new HashSet<String>();
if (Validator.isNotNull(subGenTable))
{
importList.add("java.util.List");
}
for (GenTableColumn column : columns)
{
if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType()))
{
importList.add("java.util.Date");
importList.add("com.fasterxml.jackson.annotation.JsonFormat");
}
else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType()))
{
importList.add("java.math.BigDecimal");
}
}
return importList;
}
/**
* 获取权限前缀
*
* @param moduleName 模块名称
* @param businessName 业务名称
* @return 返回权限前缀
*/
public static String getPermissionPrefix(String moduleName, String businessName)
{
return StrUtil.format("{}:{}", moduleName, businessName);
}
/**
* 获取上级菜单ID字段
*
* @param paramsObj 生成其他选项
* @return 上级菜单ID字段
*/
public static String getParentMenuId(Map<String, Object> paramsObj)
{
if (Validator.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID))
{
return Convert.toStr(paramsObj.get(GenConstants.PARENT_MENU_ID));
}
return DEFAULT_PARENT_MENU_ID;
}
/**
* 获取树编码
*
* @param paramsObj 生成其他选项
* @return 树编码
*/
public static String getTreecode(Map<String, Object> paramsObj)
{
if (Validator.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_CODE))
{
return StrUtil.toCamelCase(Convert.toStr(paramsObj.get(GenConstants.TREE_CODE)));
}
return StrUtil.EMPTY;
}
/**
* 获取树父编码
*
* @param paramsObj 生成其他选项
* @return 树父编码
*/
public static String getTreeParentCode(Map<String, Object> paramsObj)
{
if (Validator.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_PARENT_CODE))
{
return StrUtil.toCamelCase(Convert.toStr(paramsObj.get(GenConstants.TREE_PARENT_CODE)));
}
return StrUtil.EMPTY;
}
/**
* 获取树名称
*
* @param paramsObj 生成其他选项
* @return 树名称
*/
public static String getTreeName(Map<String, Object> paramsObj)
{
if (Validator.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_NAME))
{
return StrUtil.toCamelCase(Convert.toStr(paramsObj.get(GenConstants.TREE_NAME)));
}
return StrUtil.EMPTY;
}
/**
* 获取需要在哪一列上面显示展开按钮
*
* @param genTable 业务表对象
* @return 展开按钮列序号
*/
public static int getExpandColumn(GenTable genTable)
{
String options = genTable.getOptions();
Map<String, Object> paramsObj = JsonUtils.parseMap(options);
String treeName = Convert.toStr(paramsObj.get(GenConstants.TREE_NAME));
int num = 0;
for (GenTableColumn column : genTable.getColumns())
{
if (column.isList())
{
num++;
String columnName = column.getColumnName();
if (columnName.equals(treeName))
{
break;
}
}
}
return num;
}
}