feat:代码生成脚本

This commit is contained in:
xiang
2026-01-30 22:36:27 +08:00
parent 59b3dd6320
commit 2f087553eb
28 changed files with 405 additions and 698 deletions

View File

@@ -1,8 +1,8 @@
package com.xiang.xservice.application.generator.controller; package com.xiang.xservice.application.generator.controller;
import com.xiang.xservice.application.generator.entity.dto.ParamInfo; import com.xiang.xservice.application.generator.entity.dto.ParamInfo;
import com.xiang.xservice.application.generator.entity.vo.ResultVo;
import com.xiang.xservice.application.generator.service.CodeGenService; import com.xiang.xservice.application.generator.service.CodeGenService;
import com.xiang.xservice.basic.common.resp.Result;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@@ -10,6 +10,8 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/** /**
* 代码生成控制器 * 代码生成控制器
* *
@@ -18,13 +20,13 @@ import org.springframework.web.bind.annotation.RestController;
@Slf4j @Slf4j
@RequiredArgsConstructor @RequiredArgsConstructor
@RestController @RestController
@RequestMapping("/code") @RequestMapping("/system/generator/code")
public class CodeGenController { public class CodeGenController {
private final CodeGenService codeGenService; private final CodeGenService codeGenService;
@PostMapping("/generate") @PostMapping("/generate")
public ResultVo generateCode(@RequestBody ParamInfo paramInfo) throws Exception { public Result<Map<String, String>> generateCode(@RequestBody ParamInfo paramInfo) throws Exception {
return codeGenService.generateCode(paramInfo); return codeGenService.generateCode(paramInfo);
} }

View File

@@ -1,9 +1,9 @@
package com.xiang.xservice.application.generator.controller; package com.xiang.xservice.application.generator.controller;
import com.xiang.xservice.application.generator.util.ValueUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
/** /**
@@ -13,18 +13,17 @@ import org.springframework.web.servlet.ModelAndView;
*/ */
@RequiredArgsConstructor @RequiredArgsConstructor
@Controller @Controller
@RequestMapping("/generator")
public class PageController { public class PageController {
private final ValueUtil valueUtil;
@GetMapping("/") @GetMapping("/")
public ModelAndView defaultPage() { public ModelAndView defaultPage() {
return new ModelAndView("newui2").addObject("value", valueUtil); return new ModelAndView("newui2");
} }
@GetMapping("/index") @GetMapping("/index")
public ModelAndView indexPage() { public ModelAndView indexPage() {
return new ModelAndView("newui2").addObject("value", valueUtil); return new ModelAndView("newui2");
} }
} }

View File

@@ -1,7 +1,8 @@
package com.xiang.xservice.application.generator.controller; package com.xiang.xservice.application.generator.controller;
import com.xiang.xservice.application.generator.entity.vo.ResultVo; import com.xiang.xservice.application.generator.entity.dto.TemplateList;
import com.xiang.xservice.application.generator.service.TemplateService; import com.xiang.xservice.application.generator.service.TemplateService;
import com.xiang.xservice.basic.common.resp.Result;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@@ -14,14 +15,14 @@ import org.springframework.web.bind.annotation.RestController;
*/ */
@RequiredArgsConstructor @RequiredArgsConstructor
@RestController @RestController
@RequestMapping("/template") @RequestMapping("system/generator/template")
public class TemplateController { public class TemplateController {
private final TemplateService templateService; private final TemplateService templateService;
@PostMapping("/all") @PostMapping("/all")
public ResultVo getAllTemplates() throws Exception { public Result<TemplateList> getAllTemplates() throws Exception {
return ResultVo.ok(templateService.getAllTemplates()); return Result.success(templateService.getAllTemplates());
} }
} }

View File

@@ -1,21 +0,0 @@
package com.xiang.xservice.application.generator.entity;
import lombok.Data;
import java.util.List;
/**
* class info
*
* @author xuxueli 2018-05-02 20:02:34
*/
@Data
public class ClassInfo {
private String tableName;
private String originTableName;
private String className;
private String classComment;
private List<FieldInfo> fieldList;
}

View File

@@ -1,19 +0,0 @@
package com.xiang.xservice.application.generator.entity;
import lombok.Data;
/**
* field info
*
* @author xuxueli 2018-05-02 20:11:05
*/
@Data
public class FieldInfo {
private String columnName;
private String fieldName;
private String fieldClass;
private String swaggerClass;
private String fieldComment;
}

View File

@@ -1,25 +0,0 @@
package com.xiang.xservice.application.generator.entity;
import lombok.Data;
import java.util.Map;
/**
* Post data - ParamInfo
*
* @author zhengkai.blog.csdn.net
*/
@Data
public class ParamInfo {
private String tableSql;
private Map<String,Object> options;
@Data
public static class NAME_CASE_TYPE {
public static final String CAMEL_CASE = "CamelCase";
public static final String UNDER_SCORE_CASE = "UnderScoreCase";
public static final String UPPER_UNDER_SCORE_CASE = "UpperUnderScoreCase";
}
}

View File

@@ -1,18 +0,0 @@
package com.xiang.xservice.application.generator.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class TemplateConfig implements Serializable {
public static final long serialVersionUID = 66L;
Integer id;
String name;
String group;
String path;
String description;
}

View File

@@ -0,0 +1,13 @@
package com.xiang.xservice.application.generator.entity.dto;
import lombok.Data;
@Data
public class Template {
private String id;
private String name;
private String description;
}

View File

@@ -0,0 +1,11 @@
package com.xiang.xservice.application.generator.entity.dto;
import lombok.Data;
import java.util.List;
@Data
public class TemplateList {
private String group;
private List<Template> templates;
}

View File

@@ -2,7 +2,7 @@ package com.xiang.xservice.application.generator.service;
import com.xiang.xservice.application.generator.entity.dto.ParamInfo; import com.xiang.xservice.application.generator.entity.dto.ParamInfo;
import com.xiang.xservice.application.generator.entity.vo.ResultVo; import com.xiang.xservice.basic.common.resp.Result;
import java.util.Map; import java.util.Map;
@@ -20,7 +20,7 @@ public interface CodeGenService {
* @return 生成的代码映射 * @return 生成的代码映射
* @throws Exception 生成过程中的异常 * @throws Exception 生成过程中的异常
*/ */
ResultVo generateCode(ParamInfo paramInfo) throws Exception; Result<Map<String, String>> generateCode(ParamInfo paramInfo) throws Exception;
/** /**
* 根据参数获取结果 * 根据参数获取结果

View File

@@ -1,8 +1,9 @@
package com.xiang.xservice.application.generator.service; package com.xiang.xservice.application.generator.service;
import com.alibaba.fastjson2.JSONArray; import com.xiang.xservice.application.generator.entity.dto.TemplateList;
import java.io.IOException; import java.io.IOException;
import java.util.List;
/** /**
* 模板服务接口 * 模板服务接口
@@ -17,5 +18,5 @@ public interface TemplateService {
* @return 模板配置字符串 * @return 模板配置字符串
* @throws IOException IO异常 * @throws IOException IO异常
*/ */
JSONArray getAllTemplates() throws IOException; List<TemplateList> getAllTemplates() throws IOException;
} }

View File

@@ -1,28 +1,28 @@
package com.xiang.xservice.application.generator.service.impl; package com.xiang.xservice.application.generator.service.impl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xiang.xservice.application.generator.entity.dto.ClassInfo; import com.xiang.xservice.application.generator.entity.dto.ClassInfo;
import com.xiang.xservice.application.generator.entity.dto.ParamInfo; import com.xiang.xservice.application.generator.entity.dto.ParamInfo;
import com.xiang.xservice.application.generator.entity.dto.TemplateList;
import com.xiang.xservice.application.generator.entity.enums.ParserTypeEnum; import com.xiang.xservice.application.generator.entity.enums.ParserTypeEnum;
import com.xiang.xservice.application.generator.entity.vo.ResultVo;
import com.xiang.xservice.application.generator.service.CodeGenService; import com.xiang.xservice.application.generator.service.CodeGenService;
import com.xiang.xservice.application.generator.service.TemplateService; import com.xiang.xservice.application.generator.service.TemplateService;
import com.xiang.xservice.application.generator.service.parser.JsonParserService; import com.xiang.xservice.application.generator.service.parser.JsonParserService;
import com.xiang.xservice.application.generator.service.parser.SqlParserService; import com.xiang.xservice.application.generator.service.parser.SqlParserService;
import com.xiang.xservice.application.generator.util.FreemarkerUtil; import com.xiang.xservice.application.generator.util.FreemarkerUtil;
import com.xiang.xservice.application.generator.util.MapUtil; import com.xiang.xservice.application.generator.util.MapUtil;
import com.xiang.xservice.basic.common.resp.Result;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* 代码生成服务实现类 * 代码生成服务实现类
* *
* @author zhengkai.blog.csdn.net * @author xiang
*/ */
@Slf4j @Slf4j
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -34,9 +34,9 @@ public class CodeGenServiceImpl implements CodeGenService {
private final JsonParserService jsonParserService; private final JsonParserService jsonParserService;
@Override @Override
public ResultVo generateCode(ParamInfo paramInfo) throws Exception { public Result<Map<String, String>> generateCode(ParamInfo paramInfo) throws Exception {
if (paramInfo.getTableSql() == null || paramInfo.getTableSql().isEmpty()) { if (paramInfo.getTableSql() == null || paramInfo.getTableSql().isEmpty()) {
return ResultVo.error("表结构信息为空"); return Result.error("表结构信息为空");
} }
try { try {
@@ -51,10 +51,10 @@ public class CodeGenServiceImpl implements CodeGenService {
// Freemarker根据参数和模板生成代码 // Freemarker根据参数和模板生成代码
Map<String, String> result = getResultByParams(paramInfo.getOptions()); Map<String, String> result = getResultByParams(paramInfo.getOptions());
log.info("table:{} - time:{} ", MapUtil.getString(result, "tableName"), System.currentTimeMillis()); log.info("table:{} - time:{} ", MapUtil.getString(result, "tableName"), System.currentTimeMillis());
return ResultVo.ok(result); return Result.success(result);
} catch (Exception e) { } catch (Exception e) {
log.error("代码生成失败", e); log.error("代码生成失败", e);
return ResultVo.error("代码生成失败: " + e.getMessage()); return Result.error("代码生成失败: " + e.getMessage());
} }
} }
@@ -65,20 +65,18 @@ public class CodeGenServiceImpl implements CodeGenService {
// 处理模板生成逻辑 // 处理模板生成逻辑
// 解析模板配置并生成代码 // 解析模板配置并生成代码
JSONArray parentTemplates = templateService.getAllTemplates(); List<TemplateList> parentTemplates = templateService.getAllTemplates();
for (int i = 0; i < parentTemplates.size(); i++) { for (TemplateList parentTemplateObj : parentTemplates) {
JSONObject parentTemplateObj = parentTemplates.getJSONObject(i); List<com.xiang.xservice.application.generator.entity.dto.Template> childTemplates = parentTemplateObj.getTemplates();
JSONArray childTemplates = parentTemplateObj.getJSONArray("templates");
if (childTemplates != null) { if (childTemplates != null) {
for (int x = 0; x < childTemplates.size(); x++) { for (int x = 0; x < childTemplates.size(); x++) {
JSONObject childTemplate = childTemplates.getJSONObject(x); com.xiang.xservice.application.generator.entity.dto.Template childTemplate = childTemplates.get(x);
String templatePath = parentTemplateObj.getString("group") + "/" + childTemplate.getString("name") + ".ftl"; String templatePath = parentTemplateObj.getGroup() + "/" + childTemplate.getName() + ".ftl";
String generatedCode = FreemarkerUtil.processString(templatePath, params); String generatedCode = FreemarkerUtil.processString(templatePath, params);
result.put(childTemplate.getString("name"), generatedCode); result.put(childTemplate.getName(), generatedCode);
} }
} }
} }
return result; return result;
} }

View File

@@ -1,6 +1,7 @@
package com.xiang.xservice.application.generator.service.impl; package com.xiang.xservice.application.generator.service.impl;
import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONArray;
import com.xiang.xservice.application.generator.entity.dto.TemplateList;
import com.xiang.xservice.application.generator.service.TemplateService; import com.xiang.xservice.application.generator.service.TemplateService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
@@ -10,6 +11,7 @@ import org.springframework.util.StreamUtils;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.List;
/** /**
* 模板服务实现类 * 模板服务实现类
@@ -23,13 +25,13 @@ public class TemplateServiceImpl implements TemplateService {
private String templateConfig = null; private String templateConfig = null;
@Override @Override
public JSONArray getAllTemplates() throws IOException { public List<TemplateList> getAllTemplates() throws IOException {
if (templateConfig == null) { if (templateConfig == null) {
ClassPathResource resource = new ClassPathResource("template.json"); ClassPathResource resource = new ClassPathResource("template.json");
try (InputStream inputStream = resource.getInputStream()) { try (InputStream inputStream = resource.getInputStream()) {
templateConfig = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); templateConfig = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
} }
} }
return JSONArray.parseArray(templateConfig); return JSONArray.parseArray(templateConfig, TemplateList.class);
} }
} }

View File

@@ -6,7 +6,7 @@ import com.xiang.xservice.application.generator.entity.dto.ClassInfo;
import com.xiang.xservice.application.generator.entity.dto.FieldInfo; import com.xiang.xservice.application.generator.entity.dto.FieldInfo;
import com.xiang.xservice.application.generator.entity.dto.ParamInfo; import com.xiang.xservice.application.generator.entity.dto.ParamInfo;
import com.xiang.xservice.application.generator.service.parser.JsonParserService; import com.xiang.xservice.application.generator.service.parser.JsonParserService;
import com.xiang.xservice.application.generator.util.exception.CodeGenException; import com.xiang.xservice.basic.exception.BusinessException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
@@ -43,7 +43,7 @@ public class JsonParserServiceImpl implements JsonParserService {
} }
} catch (Exception e) { } catch (Exception e) {
// JSON解析失败抛出自定义异常 // JSON解析失败抛出自定义异常
throw new CodeGenException("JSON格式不正确: " + e.getMessage()); throw new BusinessException("JSON格式不正确: " + e.getMessage());
} }
return codeJavaInfo; return codeJavaInfo;
@@ -82,7 +82,7 @@ public class JsonParserServiceImpl implements JsonParserService {
} }
} }
if (fieldList.size() < 1) { if (fieldList.size() < 1) {
throw new CodeGenException("JSON解析失败"); throw new BusinessException("JSON解析失败");
} }
return fieldList; return fieldList;
} }

View File

@@ -7,8 +7,8 @@ import com.xiang.xservice.application.generator.entity.dto.ParamInfo;
import com.xiang.xservice.application.generator.service.parser.SqlParserService; import com.xiang.xservice.application.generator.service.parser.SqlParserService;
import com.xiang.xservice.application.generator.util.MapUtil; import com.xiang.xservice.application.generator.util.MapUtil;
import com.xiang.xservice.application.generator.util.StringUtilsPlus; import com.xiang.xservice.application.generator.util.StringUtilsPlus;
import com.xiang.xservice.application.generator.util.exception.SqlParseException;
import com.xiang.xservice.application.generator.util.mysqlJavaTypeUtil; import com.xiang.xservice.application.generator.util.mysqlJavaTypeUtil;
import com.xiang.xservice.basic.exception.BusinessException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.parser.CCJSqlParserUtil;
@@ -118,12 +118,12 @@ public class SqlParserServiceImpl implements SqlParserService {
statement = CCJSqlParserUtil.parse(processedSql); statement = CCJSqlParserUtil.parse(processedSql);
}catch (Exception e) { }catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new SqlParseException("SQL语法错误:"+e.getMessage()); throw new BusinessException("SQL语法错误:"+e.getMessage());
} }
// 确保是CREATE TABLE语句 // 确保是CREATE TABLE语句
if (!(statement instanceof CreateTable createTable)) { if (!(statement instanceof CreateTable createTable)) {
throw new SqlParseException("检测到SQL语句不是DLL CREATE TABLE语句"); throw new BusinessException("检测到SQL语句不是DLL CREATE TABLE语句");
} }
// 提取表名 // 提取表名

View File

@@ -6,7 +6,6 @@ import freemarker.template.Template;
import freemarker.template.TemplateException; import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler; import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
@@ -17,18 +16,14 @@ import java.util.Map;
/** /**
* freemarker tool * freemarker tool
* *
* @author xuxueli 2018-05-02 19:56:00 * @author xiang
*/ */
@Slf4j @Slf4j
@Component @Component
public class FreemarkerUtil { public class FreemarkerUtil {
@Autowired
private Configuration configuration;
/** /**
* 传入需要转义的字符串进行转义 * 传入需要转义的字符串进行转义
* 20200503 zhengkai.blog.csdn.net
*/ */
public static String escapeString(String originStr) { public static String escapeString(String originStr) {
return originStr.replaceAll("", "\\#").replaceAll("", "\\$"); return originStr.replaceAll("", "\\#").replaceAll("", "\\$");
@@ -37,14 +32,12 @@ public class FreemarkerUtil {
/** /**
* freemarker config * freemarker config
*/ */
private static Configuration freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); private static final Configuration freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
static { static {
try { try {
//2020-06-21 zhengkai 修复path问题导致jar无法运行而本地项目可以运行的bug
freemarkerConfig.setClassForTemplateLoading(FreemarkerUtil.class, "/templates/code-generator"); freemarkerConfig.setClassForTemplateLoading(FreemarkerUtil.class, "/templates/code-generator");
freemarkerConfig.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtil.class, "/templates/code-generator")); freemarkerConfig.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtil.class, "/templates/code-generator"));
//freemarkerConfig.setDirectoryForTemplateLoading(new File(templatePath, "templates/code-generator"));
freemarkerConfig.setNumberFormat("#"); freemarkerConfig.setNumberFormat("#");
freemarkerConfig.setClassicCompatible(true); freemarkerConfig.setClassicCompatible(true);
freemarkerConfig.setDefaultEncoding("UTF-8"); freemarkerConfig.setDefaultEncoding("UTF-8");
@@ -85,8 +78,7 @@ public class FreemarkerUtil {
throws IOException, TemplateException { throws IOException, TemplateException {
Template template = freemarkerConfig.getTemplate(templateName); Template template = freemarkerConfig.getTemplate(templateName);
String htmlText = escapeString(processTemplateIntoString(template, params)); return escapeString(processTemplateIntoString(template, params));
return htmlText;
} }
} }

View File

@@ -3,9 +3,6 @@ package com.xiang.xservice.application.generator.util;
import java.util.Map; import java.util.Map;
/**
* @author zhenkai.blog.csdn.net
*/
public class MapUtil { public class MapUtil {
public static String getString(Map map, String key) { public static String getString(Map map, String key) {
if (map != null && map.containsKey(key)) { if (map != null && map.containsKey(key)) {
@@ -19,6 +16,7 @@ public class MapUtil {
return ""; return "";
} }
} }
public static Integer getInteger(Map map, String key) { public static Integer getInteger(Map map, String key) {
if (map != null && map.containsKey(key)) { if (map != null && map.containsKey(key)) {
try { try {
@@ -31,6 +29,7 @@ public class MapUtil {
return 0; return 0;
} }
} }
public static Boolean getBoolean(Map map, String key) { public static Boolean getBoolean(Map map, String key) {
if (map != null && map.containsKey(key)) { if (map != null && map.containsKey(key)) {
try { try {

View File

@@ -1,16 +1,12 @@
package com.xiang.xservice.application.generator.util; package com.xiang.xservice.application.generator.util;
/**
* string tool
*
* @author xuxueli 2018-05-02 20:43:25
*/
public class StringUtilsPlus { public class StringUtilsPlus {
/** /**
* 首字母大写 * 首字母大写
* *
* @param str * @param str
*
* @return * @return
*/ */
public static String upperCaseFirst(String str) { public static String upperCaseFirst(String str) {
@@ -24,6 +20,7 @@ public class StringUtilsPlus {
* 首字母小写 * 首字母小写
* *
* @param str * @param str
*
* @return * @return
*/ */
public static String lowerCaseFirst(String str) { public static String lowerCaseFirst(String str) {
@@ -35,6 +32,7 @@ public class StringUtilsPlus {
* 下划线,转换为驼峰式 * 下划线,转换为驼峰式
* *
* @param underscoreName * @param underscoreName
*
* @return * @return
*/ */
public static String underlineToCamelCase(String underscoreName) { public static String underlineToCamelCase(String underscoreName) {
@@ -60,7 +58,7 @@ public class StringUtilsPlus {
/** /**
* 转 user_name 风格 * 转 user_name 风格
* * <p>
* 不管原始是什么风格 * 不管原始是什么风格
*/ */
public static String toUnderline(String str, boolean upperCase) { public static String toUnderline(String str, boolean upperCase) {

View File

@@ -1,53 +0,0 @@
package com.xiang.xservice.application.generator.util;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Get Value From Application.yml
* @author zhengkai.blog.csdn.net
*/
@Data
@Component
public class ValueUtil {
@Value("${OEM.title}")
public String title;
@Value("${OEM.header}")
public String header;
@Value("${OEM.version}")
public String version;
@Value("${OEM.author}")
public String author;
@Value("${OEM.keywords}")
public String keywords;
@Value("${OEM.slogan}")
public String slogan;
@Value("${OEM.copyright}")
public String copyright;
@Value("${OEM.description}")
public String description;
@Value("${OEM.packageName}")
public String packageName;
@Value("${OEM.returnUtilSuccess}")
public String returnUtilSuccess;
@Value("${OEM.returnUtilFailure}")
public String returnUtilFailure;
@Value("${OEM.outputStr}")
public String outputStr;
@Value("${OEM.mode}")
public String mode;
}

View File

@@ -1,28 +0,0 @@
package com.xiang.xservice.application.generator.util.exception;
/**
* 代码生成异常
*
* @author zhengkai.blog.csdn.net
*/
public class CodeGenException extends RuntimeException {
public CodeGenException() {
}
public CodeGenException(String message) {
super(message);
}
public CodeGenException(String message, Throwable cause) {
super(message, cause);
}
public CodeGenException(Throwable cause) {
super(cause);
}
public CodeGenException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -1,28 +0,0 @@
package com.xiang.xservice.application.generator.util.exception;
/**
* SQL解析异常
*
* @author zhengkai.blog.csdn.net
*/
public class SqlParseException extends CodeGenException {
public SqlParseException() {
}
public SqlParseException(String message) {
super(message);
}
public SqlParseException(String message, Throwable cause) {
super(message, cause);
}
public SqlParseException(Throwable cause) {
super(cause);
}
public SqlParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -2,9 +2,6 @@ package com.xiang.xservice.application.generator.util;
import java.util.HashMap; import java.util.HashMap;
/**
* @author lvyanpu
*/
public final class mysqlJavaTypeUtil { public final class mysqlJavaTypeUtil {
public static final HashMap<String, String> mysqlJavaTypeMap = new HashMap<String, String>(); public static final HashMap<String, String> mysqlJavaTypeMap = new HashMap<String, String>();
public static final HashMap<String, String> mysqlSwaggerTypeMap = new HashMap<String, String>(); public static final HashMap<String, String> mysqlSwaggerTypeMap = new HashMap<String, String>();

View File

@@ -1,11 +1,7 @@
$.inputArea = undefined; $.inputArea = undefined;
$.outputArea = undefined; $.outputArea = undefined;
$(function () { $(function () {
//powered by zhengkai.blog.csdn.net
//init input code area
$.inputArea = CodeMirror.fromTextArea(document.getElementById("inputArea"), { $.inputArea = CodeMirror.fromTextArea(document.getElementById("inputArea"), {
mode: "text/x-sql", // SQL mode: "text/x-sql", // SQL
theme: "idea", // IDEA主题 theme: "idea", // IDEA主题
@@ -70,7 +66,6 @@ const vm = new Vue({
outputJson: {} outputJson: {}
}, },
methods: { methods: {
//set the template for output 选择页面输出的模板类型
setOutputModel: function (event) { setOutputModel: function (event) {
const targetModel = event.target.innerText.trim(); const targetModel = event.target.innerText.trim();
console.log(targetModel); console.log(targetModel);
@@ -82,7 +77,6 @@ const vm = new Vue({
$.outputArea.setSize('auto', 'auto'); $.outputArea.setSize('auto', 'auto');
} }
}, },
//switch HistoricalData
switchHistoricalData: function (event) { switchHistoricalData: function (event) {
const tableName = event.target.innerText.trim(); const tableName = event.target.innerText.trim();
console.log(tableName); console.log(tableName);
@@ -118,39 +112,23 @@ const vm = new Vue({
sessionStorage.setItem(tableName, JSON.stringify(vm.outputJson)); sessionStorage.setItem(tableName, JSON.stringify(vm.outputJson));
//console.log(vm.historicalData); //console.log(vm.historicalData);
}, },
//request with formData to generate the code 根据参数生成代码
generate: function () { generate: function () {
//get value from codemirror
vm.formData.tableSql = $.inputArea.getValue(); vm.formData.tableSql = $.inputArea.getValue();
axios.post(basePath + "/code/generate", vm.formData).then(function (res) { axios.post(basePath + "/code/generate", vm.formData).then(function (res) {
if(res.status===500||res.data.code===500){ if (res.data.code === '200' && res.data.message === 'success') {
console.log(res);
error("生成失败请检查SQL语句!!!"+res.data.msg);
return;
}
setAllCookie(); setAllCookie();
//console.log(res.outputJson); vm.outputJson = res.data.data[0];
vm.outputJson = res.data.data;
//兼容后端返回数据格式 //兼容后端返回数据格式
// if(res.data){
// vm.outputJson = res.data.outputJson;
// }else {
// vm.outputJson = res.outputJson;
// }
// console.log(vm.outputJson["bootstrap-ui"]);
vm.outputStr = vm.outputJson[vm.currentSelect].trim(); vm.outputStr = vm.outputJson[vm.currentSelect].trim();
//console.log(vm.outputJson["bootstrap-ui"]);
//console.log(vm.outputStr);
$.outputArea.setValue(vm.outputStr); $.outputArea.setValue(vm.outputStr);
$.outputArea.setSize('auto', 'auto'); $.outputArea.setSize('auto', 'auto');
//add to historicalData
vm.setHistoricalData(vm.outputJson.tableName); vm.setHistoricalData(vm.outputJson.tableName);
alert("生成成功"); alert("生成成功");
return;
}
console.log(res);
error("生成失败请检查SQL语句!!!" + res.data.message);
}); });
},
copy : function (){
navigator.clipboard.writeText(vm.outputStr.trim()).then(r => {alert("已复制")});
} }
}, },
created: function () { created: function () {
@@ -158,17 +136,10 @@ const vm = new Vue({
axios.post(basePath + "/template/all", { axios.post(basePath + "/template/all", {
id: 1234 id: 1234
}).then(function (res) { }).then(function (res) {
//console.log(res.templates);
// vm.templates = JSON.parse(res.templates);
console.log('origin res', res); console.log('origin res', res);
vm.templates = res.data.data vm.templates = res.data.data
console.log('templates', vm.templates); console.log('templates', vm.templates);
//兼容后端返回数据格式 //兼容后端返回数据格式
// if(res.data){
// vm.templates = res.data.templates;
// }else {
// vm.templates = res.templates;
// }
}); });
}, },
updated: function () { updated: function () {

View File

@@ -1,6 +1,8 @@
[{ [
{
"group": "ui", "group": "ui",
"templates": [{ "templates": [
{
"id": "10", "id": "10",
"name": "swagger-ui", "name": "swagger-ui",
"description": "swagger-ui" "description": "swagger-ui"
@@ -29,7 +31,8 @@
}, },
{ {
"group": "mybatis", "group": "mybatis",
"templates": [{ "templates": [
{
"id": "20", "id": "20",
"name": "controller", "name": "controller",
"description": "controller" "description": "controller"
@@ -68,7 +71,8 @@
}, },
{ {
"group": "jpa", "group": "jpa",
"templates": [{ "templates": [
{
"id": "30", "id": "30",
"name": "entity", "name": "entity",
"description": "entity" "description": "entity"
@@ -85,10 +89,10 @@
} }
] ]
}, },
{ {
"group": "jdbc-template", "group": "jdbc-template",
"templates": [{ "templates": [
{
"id": "40", "id": "40",
"name": "jtdao", "name": "jtdao",
"description": "jtdao" "description": "jtdao"
@@ -100,10 +104,10 @@
} }
] ]
}, },
{ {
"group": "beetlsql", "group": "beetlsql",
"templates": [{ "templates": [
{
"id": "50", "id": "50",
"name": "beetlmd", "name": "beetlmd",
"description": "beetlmd" "description": "beetlmd"
@@ -120,10 +124,10 @@
} }
] ]
}, },
{ {
"group": "mybatis-plus", "group": "mybatis-plus",
"templates": [{ "templates": [
{
"id": "60", "id": "60",
"name": "pluscontroller", "name": "pluscontroller",
"description": "pluscontroller" "description": "pluscontroller"
@@ -145,10 +149,10 @@
} }
] ]
}, },
{ {
"group": "util", "group": "util",
"templates": [{ "templates": [
{
"id": "70", "id": "70",
"name": "beanutil", "name": "beanutil",
"description": "beanutil" "description": "beanutil"
@@ -175,10 +179,10 @@
} }
] ]
}, },
{ {
"group": "common-mapper", "group": "common-mapper",
"templates": [{ "templates": [
{
"id": "81", "id": "81",
"name": "tkentity", "name": "tkentity",
"description": "tkentity" "description": "tkentity"
@@ -190,10 +194,10 @@
} }
] ]
}, },
{ {
"group": "renren-fast", "group": "renren-fast",
"templates": [{ "templates": [
{
"id": "91", "id": "91",
"name": "menu-sql", "name": "menu-sql",
"description": "menu-sql" "description": "menu-sql"
@@ -232,7 +236,8 @@
}, },
{ {
"group": "jpa-starp", "group": "jpa-starp",
"templates": [{ "templates": [
{
"id": "101", "id": "101",
"name": "starp-entity", "name": "starp-entity",
"description": "entity" "description": "entity"
@@ -251,11 +256,13 @@
}, },
{ {
"group": "bi", "group": "bi",
"templates": [{ "templates": [
{
"id": "201", "id": "201",
"name": "qliksense", "name": "qliksense",
"description": "qlik sense" "description": "qlik sense"
}] }
]
}, },
{ {
"group": "cloud", "group": "cloud",

View File

@@ -1,26 +1,35 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>${(value.title)!!}</title> <title>代码生成</title>
<meta name="keywords" content="${(value.keywords)!!}">
<script> <script>
/*统计代码,便于统计流量,请勿移除,谢谢!*/ var basePath = "/system/generator";
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?97fd5ca1a4298ac8349c7e0de9029a0f";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
//set base path for fixing the revertProxy forwarding path issue
var basePath = "${request.contextPath}";
console.log("basePath",basePath)
</script> </script>
<#if value.mode=='local'> <script src="/statics/libs/jquery/jquery.min.js"></script>
<#include "/newui-import-local.html"> <script src="/statics/libs/vue/vue.min.js"></script>
<#else> <script src="/statics/libs/axios/axios.min.js"></script>
<#include "/newui-import-CDN.html"> <script src="/statics/libs/element-ui/index.min.js"></script>
</#if> <link href="/statics/libs/element-ui/index.min.css" type="text/css" rel="stylesheet" />
<!-- bootstrap -->
<script src="/statics/libs/bootstrap/bootstrap.bundle.min.js" type="application/javascript"></script>
<link href="/statics/libs/bootstrap/bootstrap.min.css" type="text/css" rel="stylesheet" />
<!-- 引入 Bootstrap Icons CSS -->
<link href="/statics/libs/bootstrap-icons/bootstrap-icons.min.css" type="text/css" rel="stylesheet" />
<!--common.js-->
<script src="/statics/js/common.js"></script>
<!-- <link rel="stylesheet" href="/statics/css/main.css"> -->
<script src="/statics/libs/toastr.js/toastr.min.js"></script>
<!-- Toastr CSS -->
<link href="/statics/libs/toastr.js/toastr.min.css" rtype="text/css" rel="stylesheet" >
<!-- import codemirror -->
<script src="/statics/libs/codemirror/codemirror.min.js"></script>
<script src="/statics/libs/codemirror/mode/sql/sql.min.js"></script>
<script src="/statics/libs/codemirror/mode/clike/clike.min.js"></script>
<link href="/statics/libs/codemirror/codemirror.min.css" type="text/css" rel="stylesheet" >
<link href="/statics/libs/codemirror/theme/idea.min.css" type="text/css" rel="stylesheet" >

View File

@@ -1,31 +0,0 @@
<!--###################################################-->
<!--### StaticFile CDN : by https://www.staticfile.org/ -->
<!--###################################################-->
<!--jquery | vue | element-ui | axios-->
<script src="//cdn.staticfile.net/jquery/3.6.0/jquery.min.js"></script>
<script src="//cdn.staticfile.net/vue/2.6.14/vue.min.js"></script>
<script src="//cdn.staticfile.net/axios/0.26.0/axios.min.js"></script>
<script src="//cdn.staticfile.net/element-ui/2.15.7/index.min.js"></script>
<link href="//cdn.staticfile.net/element-ui/2.15.7/theme-chalk/index.min.css" type="text/css" rel="stylesheet" />
<!-- bootstrap -->
<script src="//cdn.staticfile.net/bootstrap/5.1.3/js/bootstrap.bundle.min.js" type="application/javascript"></script>
<link href="//cdn.staticfile.net/bootstrap/5.1.3/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
<!-- 引入 Bootstrap Icons CSS -->
<link href="//cdn.staticfile.net/bootstrap-icons/1.8.1/font/bootstrap-icons.min.css" type="text/css" rel="stylesheet" />
<!--common.js-->
<script src="${request.contextPath}/statics/js/common.js"></script>
<!-- <link rel="stylesheet" href="${request.contextPath}/statics/css/main.css"> -->
<script src="//cdn.staticfile.net/toastr.js/2.1.4/toastr.min.js"></script>
<!-- Toastr CSS -->
<link href="//cdn.staticfile.net/toastr.js/2.1.4/toastr.min.css" rtype="text/css" rel="stylesheet" >
<!-- import codemirror -->
<script src="//cdn.staticfile.net/codemirror/5.65.2/codemirror.min.js"></script>
<script src="//cdn.staticfile.net/codemirror/5.65.2/mode/sql/sql.min.js"></script>
<script src="//cdn.staticfile.net/codemirror/5.65.2/mode/clike/clike.min.js" type="application/javascript"></script>
<link href="//cdn.staticfile.net/codemirror/5.65.2/codemirror.min.css" type="text/css" rel="stylesheet" >
<link href="//cdn.staticfile.net/codemirror/5.65.2/theme/idea.min.css" type="text/css" rel="stylesheet" >

View File

@@ -1,31 +0,0 @@
<!--###################################################-->
<!--### CDN version -->
<!--###################################################-->
<!--jquery | vue | element-ui | axios-->
<script src="${request.contextPath}/statics/libs/jquery/jquery.min.js"></script>
<script src="${request.contextPath}/statics/libs/vue/vue.min.js"></script>
<script src="${request.contextPath}/statics/libs/axios/axios.min.js"></script>
<script src="${request.contextPath}/statics/libs/element-ui/index.min.js"></script>
<link href="${request.contextPath}/statics/libs/element-ui/index.min.css" type="text/css" rel="stylesheet" />
<!-- bootstrap -->
<script src="${request.contextPath}/statics/libs/bootstrap/bootstrap.bundle.min.js" type="application/javascript"></script>
<link href="${request.contextPath}/statics/libs/bootstrap/bootstrap.min.css" type="text/css" rel="stylesheet" />
<!-- 引入 Bootstrap Icons CSS -->
<link href="${request.contextPath}/statics/libs/bootstrap-icons/bootstrap-icons.min.css" type="text/css" rel="stylesheet" />
<!--common.js-->
<script src="${request.contextPath}/statics/js/common.js"></script>
<!-- <link rel="stylesheet" href="${request.contextPath}/statics/css/main.css"> -->
<script src="${request.contextPath}/statics/libs/toastr.js/toastr.min.js"></script>
<!-- Toastr CSS -->
<link href="${request.contextPath}/statics/libs/toastr.js/toastr.min.css" rtype="text/css" rel="stylesheet" >
<!-- import codemirror -->
<script src="${request.contextPath}/statics/libs/codemirror/codemirror.min.js"></script>
<script src="${request.contextPath}/statics/libs/codemirror/mode/sql/sql.min.js"></script>
<script src="${request.contextPath}/statics/libs/codemirror/mode/clike/clike.min.js"></script>
<link href="${request.contextPath}/statics/libs/codemirror/codemirror.min.css" type="text/css" rel="stylesheet" >
<link href="${request.contextPath}/statics/libs/codemirror/theme/idea.min.css" type="text/css" rel="stylesheet" >

View File

@@ -49,26 +49,16 @@
z-index: 1000; z-index: 1000;
} }
.last-card { .last-card {
margin-bottom: 70px; /* 增加输出代码区域与底部的距离 */ margin-bottom: 70px;
} }
</style> </style>
</head> </head>
<body> <body>
<div id="app"> <div id="app">
<div class="header-bar">
<div class="logo">
<i class="bi bi-code"></i>
${(value.title)!!}
</div>
<small>${(value.slogan)!!}</small>
<div class="links">
<a href="https://github.com/moshowgame/SpringBootCodeGenerator/" target="_blank">GitHub</a> <a href="https://zhengkai.blog.csdn.net/" target="_blank">CSDN</a>
</div>
</div>
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<blockquote class="quote-secondary"> <blockquote class="quote-secondary">
${(value.description)!!} 欢迎使用Java代码生成工具
</blockquote> </blockquote>
<div class="col-lg-12"> <div class="col-lg-12">
<div id="rrapp" v-cloak> <div id="rrapp" v-cloak>
@@ -91,7 +81,7 @@
<hr> <hr>
<div class="card"> <div class="card">
<div class="card-header"> <div class="card-header">
<h5 class="card-title m-0">生成设置</h5> <h5 class="card-title m-0">生成设置&nbsp;&nbsp;&nbsp;&nbsp;<el-button type="primary" icon="el-icon-caret-right" @click="generate">生成</el-button></h5>
<div class="card-tools"> <div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="折叠"> <button type="button" class="btn btn-tool" data-card-widget="collapse" title="折叠">
<i class="fas fa-minus"></i> <i class="fas fa-minus"></i>
@@ -172,29 +162,6 @@
</el-form-item> </el-form-item>
</div> </div>
</div> </div>
<hr>
<div class="card">
<div class="card-header">
<el-button type="primary" icon="el-icon-caret-right" @click="generate">生成</el-button>
<el-button type="primary" icon="el-icon-document-copy" @click="copy" plain>复制</el-button>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="折叠">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<span v-if="historicalData.length > 0">
<el-button-group>
<el-button type="primary" plain disabled round>历史记录</el-button>
<span v-for="(item, index) in historicalData" :key="index">
<el-button @click="switchHistoricalData">{{ item }}</el-button>
</span>
</el-button-group>
</span>
</div>
</div>
<hr> <hr>
<div class="card"> <div class="card">
<div class="card-header"> <div class="card-header">
@@ -246,14 +213,8 @@
</div> </div>
</div> </div>
<script src="${request.contextPath}/statics/js/main.js"></script> <script src="/statics/js/main.js"></script>
<script> <script>
//console.log(vm);
vm.formData.options.authorName="${(value.author)!!}";
vm.formData.options.packageName="${(value.packageName)!!}";
vm.formData.options.returnUtilSuccess="${(value.returnUtilSuccess)!!}";
vm.formData.options.returnUtilFailure="${(value.returnUtilFailure)!!}";
vm.outputStr="${(value.outputStr)!!}";
loadAllCookie() loadAllCookie()
</script> </script>
</body> </body>