🔖 发布一个版本。 v1.4.0 新增代码生成

This commit is contained in:
冷冷 committed 2018-08-02 22:16:14 +08:00
1 parent 4e6ce28340
commit cbceb44fb4
18 files changed
+246 -99

No files matched your search

@@ -19,6 +19,7 @@ package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.SysGeneratorService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
@@ -35,7 +36,7 @@ import java.util.Map;
*/
@RestController
@AllArgsConstructor
@RequestMapping("/generator" )
@RequestMapping("/generator")
public class SysGeneratorController {
private final SysGeneratorService sysGeneratorService;
@@ -45,7 +46,7 @@ public class SysGeneratorController {
* @param params 参数集
* @return 数据库表
*/
@GetMapping("/page" )
@GetMapping("/page")
public Page list(@RequestParam Map<String, Object> params) {
return sysGeneratorService.queryPage(params);
}
@@ -53,14 +54,14 @@ public class SysGeneratorController {
/**
* 生成代码
*/
@GetMapping("/code/{tableName}" )
public void code(@PathVariable String tableName, HttpServletResponse response) throws IOException {
byte[] data = sysGeneratorService.generatorCode(new String[]{tableName});
@PostMapping("/code")
public void code(@RequestBody GenConfig genConfig, HttpServletResponse response) throws IOException {
byte[] data = sysGeneratorService.generatorCode(genConfig);
response.reset();
response.setHeader("Content-Disposition", String.format("attachment; filename=%s.zip", tableName));
response.setHeader("Content-Disposition", String.format("attachment; filename=%s.zip", genConfig.getTableName()));
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8" );
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.entity;
import lombok.Data;
/**
* @author lengleng
* @date 2018/8/2
* 生成配置
*/
@Data
public class GenConfig {
/**
* 包名
*/
private String packageName;
/**
* 作者
*/
private String author;
/**
* 模块名称
*/
private String moduleName;
/**
* 表前缀
*/
private String tablePrefix;
/**
* 表名称
*/
private String tableName;
/**
* 表备注
*/
private String comments;
}
@@ -18,7 +18,7 @@
package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.plugins.Page;
import com.pig4cloud.pigx.common.core.util.Query;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import java.util.Map;
@@ -33,7 +33,7 @@ public interface SysGeneratorService {
* @param tableNames 表名称
* @return
*/
byte[] generatorCode(String[] tableNames);
byte[] generatorCode(GenConfig tableNames);
/**
* 分页查询表
@@ -20,6 +20,7 @@ package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.mapper.SysGeneratorMapper;
import com.pig4cloud.pigx.codegen.service.SysGeneratorService;
import com.pig4cloud.pigx.codegen.util.GenUtils;
@@ -69,22 +70,20 @@ public class SysGeneratorServiceImpl implements SysGeneratorService {
/**
* 生成代码
*
* @param tableNames 表名称
* @param genConfig 生成配置
* @return
*/
@Override
public byte[] generatorCode(String[] tableNames) {
public byte[] generatorCode(GenConfig genConfig) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) {
//查询表信息
Map<String, String> table = queryTable(tableName);
//查询列信息
List<Map<String, String>> columns = queryColumns(tableName);
//生成代码
GenUtils.generatorCode(table, columns, zip);
}
//查询表信息
Map<String, String> table = queryTable(genConfig.getTableName());
//查询列信息
List<Map<String, String>> columns = queryColumns(genConfig.getTableName());
//生成代码
GenUtils.generatorCode(genConfig, table, columns, zip);
IoUtil.close(zip);
return outputStream.toByteArray();
}
@@ -20,7 +20,9 @@ package com.pig4cloud.pigx.codegen.util;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.entity.TableEntity;
import com.pig4cloud.pigx.common.core.exception.CheckedException;
import lombok.extern.slf4j.Slf4j;
@@ -49,47 +51,60 @@ import java.util.zip.ZipOutputStream;
@Slf4j
public class GenUtils {
public static final String ENTITY_JAVA_VM = "Entity.java.vm";
public static final String MAPPER_JAVA_VM = "Mapper.java.vm";
public static final String SERVICE_JAVA_VM = "Service.java.vm";
public static final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm";
public static final String CONTROLLER_JAVA_VM = "Controller.java.vm";
public static final String MAPPER_XML_VM = "Mapper.xml.vm";
public static final String MENU_SQL_VM = "menu.sql.vm";
public static final String INDEX_VUE_VM = "index.vue.vm";
public static final String API_JS_VM = "api.js.vm";
public static final String CRUD_JS_VM = "crud.js.vm";
private static final String ENTITY_JAVA_VM = "Entity.java.vm";
private static final String MAPPER_JAVA_VM = "Mapper.java.vm";
private static final String SERVICE_JAVA_VM = "Service.java.vm";
private static final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm";
private static final String CONTROLLER_JAVA_VM = "Controller.java.vm";
private static final String MAPPER_XML_VM = "Mapper.xml.vm";
private static final String MENU_SQL_VM = "menu.sql.vm";
private static final String INDEX_VUE_VM = "index.vue.vm";
private static final String API_JS_VM = "api.js.vm";
private static final String CRUD_JS_VM = "crud.js.vm";
public static List<String> getTemplates() {
private static List<String> getTemplates() {
List<String> templates = new ArrayList<>();
templates.add("template/Entity.java.vm" );
templates.add("template/Mapper.java.vm" );
templates.add("template/Mapper.xml.vm" );
templates.add("template/Service.java.vm" );
templates.add("template/ServiceImpl.java.vm" );
templates.add("template/Controller.java.vm" );
templates.add("template/menu.sql.vm" );
templates.add("template/Entity.java.vm");
templates.add("template/Mapper.java.vm");
templates.add("template/Mapper.xml.vm");
templates.add("template/Service.java.vm");
templates.add("template/ServiceImpl.java.vm");
templates.add("template/Controller.java.vm");
templates.add("template/menu.sql.vm");
templates.add("template/index.vue.vm" );
templates.add("template/api.js.vm" );
templates.add("template/crud.js.vm" );
templates.add("template/index.vue.vm");
templates.add("template/api.js.vm");
templates.add("template/crud.js.vm");
return templates;
}
/**
* 生成代码
*/
public static void generatorCode(Map<String, String> table,
public static void generatorCode(GenConfig genConfig, Map<String, String> table,
List<Map<String, String>> columns, ZipOutputStream zip) {
//配置信息
Configuration config = getConfig();
boolean hasBigDecimal = false;
//表信息
TableEntity tableEntity = new TableEntity();
tableEntity.setTableName(table.get("tableName" ));
tableEntity.setComments(table.get("tableComment" ));
tableEntity.setTableName(table.get("tableName"));
if (StrUtil.isNotBlank(genConfig.getComments())) {
tableEntity.setComments(genConfig.getComments());
} else {
tableEntity.setComments(table.get("tableComment"));
}
String tablePrefix;
if (StrUtil.isNotBlank(genConfig.getTablePrefix())) {
tablePrefix = genConfig.getTablePrefix();
} else {
tablePrefix = config.getString("tablePrefix");
}
//表名转换成Java类名
String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix" ));
String className = tableToJava(tableEntity.getTableName(), tablePrefix);
tableEntity.setCaseClassName(className);
tableEntity.setLowerClassName(StringUtils.uncapitalize(className));
@@ -97,10 +112,10 @@ public class GenUtils {
List<ColumnEntity> columnList = new ArrayList<>();
for (Map<String, String> column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setColumnName(column.get("columnName" ));
columnEntity.setDataType(column.get("dataType" ));
columnEntity.setComments(column.get("columnComment" ));
columnEntity.setExtra(column.get("extra" ));
columnEntity.setColumnName(column.get("columnName"));
columnEntity.setDataType(column.get("dataType"));
columnEntity.setComments(column.get("columnComment"));
columnEntity.setExtra(column.get("extra"));
//列名转换成Java属性名
String attrName = columnToJava(columnEntity.getColumnName());
@@ -108,13 +123,13 @@ public class GenUtils {
columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));
//列的数据类型,转换成Java类型
String attrType = config.getString(columnEntity.getDataType(), "unknowType" );
String attrType = config.getString(columnEntity.getDataType(), "unknowType");
columnEntity.setAttrType(attrType);
if (!hasBigDecimal && attrType.equals("BigDecimal" )) {
if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
hasBigDecimal = true;
}
//是否主键
if ("PRI".equalsIgnoreCase(column.get("columnKey" )) && tableEntity.getPk() == null) {
if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
tableEntity.setPk(columnEntity);
}
@@ -129,25 +144,44 @@ public class GenUtils {
//设置velocity资源加载器
Properties prop = new Properties();
prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" );
prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
String mainPath = config.getString("mainPath" );
mainPath = StringUtils.isBlank(mainPath) ? "com.pig4cloud.pigx" : mainPath;
//封装模板数据
Map<String, Object> map = new HashMap<>(16);
map.put("tableName", tableEntity.getTableName());
map.put("comments", tableEntity.getComments());
map.put("pk", tableEntity.getPk());
map.put("className", tableEntity.getCaseClassName());
map.put("classname", tableEntity.getLowerClassName());
map.put("pathName", tableEntity.getLowerClassName().toLowerCase());
map.put("columns", tableEntity.getColumns());
map.put("hasBigDecimal", hasBigDecimal);
map.put("mainPath", mainPath);
map.put("package", config.getString("package" ));
map.put("moduleName", config.getString("moduleName" ));
map.put("author", config.getString("author" ));
map.put("datetime", DateUtil.now());
if (StrUtil.isNotBlank(genConfig.getComments())) {
map.put("comments", genConfig.getComments());
} else {
map.put("comments", tableEntity.getComments());
}
if (StrUtil.isNotBlank(genConfig.getAuthor())) {
map.put("author", genConfig.getAuthor());
} else {
map.put("author", config.getString("author"));
}
if (StrUtil.isNotBlank(genConfig.getModuleName())) {
map.put("moduleName", genConfig.getModuleName());
} else {
map.put("moduleName", config.getString("moduleName"));
}
if (StrUtil.isNotBlank(genConfig.getPackageName())) {
map.put("package", genConfig.getPackageName());
map.put("mainPath", genConfig.getPackageName());
} else {
map.put("package", config.getString("package"));
map.put("mainPath", config.getString("mainPath"));
}
VelocityContext context = new VelocityContext(map);
//获取模板列表
@@ -162,7 +196,7 @@ public class GenUtils {
//添加到zip
zip.putNextEntry(new ZipEntry(Objects
.requireNonNull(getFileName(template, tableEntity.getCaseClassName()
, config.getString("package" ), config.getString("moduleName" )))));
, map.get("package").toString(), map.get("moduleName").toString()))));
IoUtil.write(zip, CharsetUtil.UTF_8, false, sw.toString());
IoUtil.close(sw);
zip.closeEntry();
@@ -177,7 +211,7 @@ public class GenUtils {
* 列名转换成Java属性名
*/
private static String columnToJava(String columnName) {
return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "" );
return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
}
/**
@@ -185,7 +219,7 @@ public class GenUtils {
*/
private static String tableToJava(String tableName, String tablePrefix) {
if (StringUtils.isNotBlank(tablePrefix)) {
tableName = tableName.replace(tablePrefix, "" );
tableName = tableName.replace(tablePrefix, "");
}
return columnToJava(tableName);
}
@@ -193,9 +227,9 @@ public class GenUtils {
/**
* 获取配置信息
*/
public static Configuration getConfig() {
private static Configuration getConfig() {
try {
return new PropertiesConfiguration("generator.properties" );
return new PropertiesConfiguration("generator.properties");
} catch (ConfigurationException e) {
throw new CheckedException("获取配置文件失败,", e);
}
@@ -204,8 +238,8 @@ public class GenUtils {
/**
* 获取文件名
*/
public static String getFileName(String template, String className, String packageName, String moduleName) {
String packagePath = "pigx" + File.separator + "main" + File.separator + "java" + File.separator;
private static String getFileName(String template, String className, String packageName, String moduleName) {
String packagePath = "pigx" + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator;
if (StringUtils.isNotBlank(packageName)) {
packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
}
@@ -231,7 +265,7 @@ public class GenUtils {
}
if (template.contains(MAPPER_XML_VM)) {
return "pigx" + File.separator + "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + moduleName + File.separator + className + "Mapper.xml";
return "pigx" + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + moduleName + File.separator + className + "Mapper.xml";
}
if (template.contains(MENU_SQL_VM)) {
@@ -249,7 +283,7 @@ public class GenUtils {
if (template.contains(CRUD_JS_VM)) {
return "pigx-ui" + File.separator + "src" + File.separator + "const" +
File.separator + "curd" + File.separator + className.toLowerCase() + ".js";
File.separator + "crud" + File.separator + className.toLowerCase() + ".js";
}
return null;
@@ -14,7 +14,7 @@ tablePrefix=tb_
tinyint=Integer
smallint=Integer
mediumint=Integer
int=Integer
int=Integer
integer=Integer
bigint=Long
float=Float
@@ -5,7 +5,7 @@ import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.pig4cloud.pigx.common.core.constant.CommonConstant;
import com.baomidou.mybatisplus.plugins.Page;
import com.pig4cloud.pigx.common.core.util.Query;
import ${package}.${moduleName}.entity.${className};
@@ -21,7 +21,7 @@ import java.util.Map;
* @date ${datetime}
*/
@RestController
@RequestMapping("${moduleName}/${pathName}")
@RequestMapping("/${pathName}")
public class ${className}Controller {
@Autowired
private ${className}Service ${classname}Service;
@@ -34,7 +34,6 @@ public class ${className}Controller {
*/
@GetMapping("/page")
public Page page(@RequestParam Map<String, Object> params) {
params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
return ${classname}Service.selectPage(new Query<>(params), new EntityWrapper<>());
}
@@ -1,5 +1,6 @@
package ${package}.${moduleName}.entity;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
@@ -19,7 +20,7 @@ import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("${tableName}")
public class ${className} implements Serializable {
public class ${className} extends Model<${className}> {
private static final long serialVersionUID = 1L;
#foreach ($column in $columns)
@@ -31,4 +32,12 @@ public class ${className} implements Serializable {
#end
private $column.attrType $column.lowerAttrName;
#end
/**
* 主键值
*/
@Override
protected Serializable pkVal() {
return this.$pk.columnName;
}
}
@@ -6,7 +6,7 @@
<!-- 可根据自己的需求,是否要使用 -->
<resultMap type="${package}.${moduleName}.entity.${className}" id="${classname}Map">
#foreach($column in $columns)
<result property="${column.attrname}" column="${column.columnName}"/>
<result property="${column.lowerAttrName}" column="${column.columnName}"/>
#end
</resultMap>
@@ -1,11 +1,13 @@
-- 该脚本不要执行,请完善 ID 对应关系,注意层级关系 !!!!
-- 菜单SQL
insert into `pigx`.`sys_menu` ( `parent_id`, `component`, `permission`, `type`, `path`, `icon`, `menu_id`, `del_flag`, `create_time`, `sort`, `update_time`, `name`)
values ( '1', 'views/${moduleName}/${pathName}/index', '', '0', 'client', 'icon-bangzhushouji', '8', '0', '2018-01-20 13:17:19', '8', '2018-07-29 13:38:19', '${comments}管理');
values ( '1', 'views/${moduleName}/${pathName}/index', '菜单ID', '0', '${pathName}', 'icon-bangzhushouji', '8', '0', '2018-01-20 13:17:19', '8', '2018-07-29 13:38:19', '${comments}管理');
-- 菜单对应按钮SQL
insert into `pigx`.`sys_menu` ( `parent_id`, `component`, `permission`, `type`, `path`, `icon`, `menu_id`, `del_flag`, `create_time`, `sort`, `update_time`, `name`)
values ( '8', null, '${moduleName}_${pathName}_add', '1', null, '1', '81', '0', '2018-05-15 21:35:18', '0', '2018-07-29 13:38:59', '${comments}新增');
values ( '子按钮ID1', null, '${moduleName}_${pathName}_add', '1', null, '1', '81', '0', '2018-05-15 21:35:18', '0', '2018-07-29 13:38:59', '${comments}新增');
insert into `pigx`.`sys_menu` ( `parent_id`, `component`, `permission`, `type`, `path`, `icon`, `menu_id`, `del_flag`, `create_time`, `sort`, `update_time`, `name`)
values ( '8', null, '${moduleName}_${pathName}_edit', '1', null, '1', '81', '0', '2018-05-15 21:35:18', '1', '2018-07-29 13:38:59', '${comments}修改');
values ( '子按钮ID2', null, '${moduleName}_${pathName}_edit', '1', null, '1', '81', '0', '2018-05-15 21:35:18', '1', '2018-07-29 13:38:59', '${comments}修改');
insert into `pigx`.`sys_menu` ( `parent_id`, `component`, `permission`, `type`, `path`, `icon`, `menu_id`, `del_flag`, `create_time`, `sort`, `update_time`, `name`)
values ( '8', null, '${moduleName}_${pathName}_del', '1', null, '1', '81', '0', '2018-05-15 21:35:18', '2', '2018-07-29 13:38:59', '${comments}删除');
values ( '子按钮ID3', null, '${moduleName}_${pathName}_del', '1', null, '1', '81', '0', '2018-05-15 21:35:18', '2', '2018-07-29 13:38:59', '${comments}删除');