From 4c1b190fd0398e179f8f6ff58cf6b12565cade73 Mon Sep 17 00:00:00 2001 From: lizhenyu1 Date: Wed, 6 Mar 2019 17:48:38 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=AF=E8=A7=86=E5=8C=96=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ReadMe.md | 29 ++-- build.gradle | 16 +- .../java/autojcode/AutoCodeApplication.java | 3 +- .../{ => controller}/CodeGenerateUtils.java | 52 ++++--- .../autojcode/controller/IndexController.java | 16 ++ .../{ => controller}/JcodeController.java | 17 ++- .../java/autojcode/domain/ResultUtil.java | 8 + .../java/autojcode/enums/DataBaseEnum.java | 2 +- src/main/resources/application.yml | 9 +- src/main/resources/static/css/index.css | 5 + src/main/resources/static/js/index.js | 110 ++++++++++++++ .../resources/templates/MapperProvider.ftl | 4 +- src/main/resources/templates/views/index.ftl | 141 ++++++++++++++++++ 13 files changed, 358 insertions(+), 54 deletions(-) rename src/main/java/autojcode/{ => controller}/CodeGenerateUtils.java (89%) create mode 100644 src/main/java/autojcode/controller/IndexController.java rename src/main/java/autojcode/{ => controller}/JcodeController.java (60%) create mode 100644 src/main/resources/static/css/index.css create mode 100644 src/main/resources/static/js/index.js create mode 100644 src/main/resources/templates/views/index.ftl diff --git a/ReadMe.md b/ReadMe.md index a15eef8..3f4b7fe 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -1,19 +1,26 @@ -#### 简介 +### 简介 >- 后台程序工具化,连接mysql数据库一键生成规范统一的增删改查操作 >- 包括鉴权、异常处理、接口规范返回、生成表的所有增删该查 ->- 生成框架:Spring Boot 1.5 + Gradle + Mybatis + Swagger2 +>- 生成框架:Spring MVC + Spring Boot 1.5 + Gradle + Mybatis + MySQL + Swagger2 >- 支持二次开发 -#### 项目采用框架 ->- Spring Boot、Gradle、freemarkTemplate -#### TODOLIST --[ ] 前端代码自动生成 +### 项目采用框架 +>- Spring MVC、Spring Boot、Gradle、freemarkTemplate、Swagger2、MySQL +### TODOLIST +-[ ] 前端代码自动集成 +-[ ] redis集群支持 +-[ ] 鉴权集成redis +-[ ] 定时任务自定义(低优) +-[ ] 调整ID字段兼容String和Long类型 -[X] 1.0版本 -#### 项目初始化 +### 项目初始化 +##### 前期准备 +>- 数据库创建表(做好字段备注) +>- 每个表内字段最好有ID字段,目前只支持String类型 +##### 使用工具 >- 1.启动项目 ->- 2.访问 localhost:9999/swagger-ui.html ->- 3.controller里只有一个接口,按照接口入参规范输入 +>- 2.访问 localhost:9090 >- 4.默认生成路径 C:/autoJcode -#### 项目结构 +### 项目结构 >项目标识 >
| - common >
| - controller @@ -28,4 +35,4 @@ >
| - application-prod.yml >
| - logback-spring.xml >
build.gradle -#### 有不足,请多指教 \ No newline at end of file +### 有不足,请多指教 \ No newline at end of file diff --git a/build.gradle b/build.gradle index 96e9c08..87cc3f1 100644 --- a/build.gradle +++ b/build.gradle @@ -10,15 +10,6 @@ buildscript { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } -/*buildscript { - repositories { - maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/' } - maven{ url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'} - } - dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") - } -}*/ allprojects { repositories { maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'} @@ -40,13 +31,8 @@ repositories { dependencies { compile 'org.springframework.boot:spring-boot-starter-web' compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0' - compile group: 'freemarker', name: 'freemarker', version: '2.3.9' - // https://mvnrepository.com/artifact/mysql/mysql-connector-java + compile 'org.springframework.boot:spring-boot-starter-freemarker' compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.12' - // https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 compile 'io.springfox:springfox-swagger2:2.6.1' - // https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui compile 'io.springfox:springfox-swagger-ui:2.6.1' - - /* compile "org.springframework.boot:spring-boot-configuration-processor"*/ } diff --git a/src/main/java/autojcode/AutoCodeApplication.java b/src/main/java/autojcode/AutoCodeApplication.java index 1609878..ac0e821 100644 --- a/src/main/java/autojcode/AutoCodeApplication.java +++ b/src/main/java/autojcode/AutoCodeApplication.java @@ -8,9 +8,8 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Created by lizhenyu on 2018/5/11 */ -@EnableSwagger2 +//@EnableSwagger2 @SpringBootApplication -//@ComponentScan(basePackages = "autojcode.utils") public class AutoCodeApplication { public static void main(String[] args) { SpringApplication.run(AutoCodeApplication.class, args); diff --git a/src/main/java/autojcode/CodeGenerateUtils.java b/src/main/java/autojcode/controller/CodeGenerateUtils.java similarity index 89% rename from src/main/java/autojcode/CodeGenerateUtils.java rename to src/main/java/autojcode/controller/CodeGenerateUtils.java index c5f0dca..5f46dd7 100644 --- a/src/main/java/autojcode/CodeGenerateUtils.java +++ b/src/main/java/autojcode/controller/CodeGenerateUtils.java @@ -1,4 +1,4 @@ -package autojcode; +package autojcode.controller; import autojcode.config.FreeMarkerTemplateUtils; import autojcode.domain.TableColumn; @@ -15,6 +15,7 @@ import java.io.*; import java.sql.*; import java.util.*; import java.util.Date; + import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; @@ -23,11 +24,27 @@ import org.springframework.util.ObjectUtils; */ @Service public class CodeGenerateUtils { + //private static final Logger logger = LoggerFactory.getLogger(CodeGenerateUtils.class); private JcodeProperties jcodeProperties; + public List getDbTest(JcodeProperties properties) throws Exception { + try { + jcodeProperties = properties; + List tableNames = new ArrayList<>(); + ResultSet resultSet = getDbTables("%"); + while (resultSet.next()) { + tableNames.add(resultSet.getString("TABLE_NAME")); + } + return tableNames; + } catch (Exception e) { + throw e; + } + } + /** * 数据库整体自动生成代码 + * * @param properties 配置参数 * @return * @throws MyBizException @@ -35,11 +52,10 @@ public class CodeGenerateUtils { public String autoJcodeForDb(JcodeProperties properties) throws MyBizException { StringBuilder result = new StringBuilder(); try { - - if (ObjectUtils.isEmpty(properties.getGroup())||ObjectUtils.isEmpty(properties.getArtifact()) + if (ObjectUtils.isEmpty(properties.getGroup()) || ObjectUtils.isEmpty(properties.getArtifact()) || ObjectUtils.isEmpty(properties.getDb()) - ) { - throw new MyBizException(-1, "PackageName,Db必填"); + ) { + throw new MyBizException(-1, "group或Artifact不存在"); } jcodeProperties = properties; @@ -49,20 +65,18 @@ public class CodeGenerateUtils { jcodeProperties.setTableName("%"); } String[] tables = jcodeProperties.getTableName().split(","); - result.append("【生成路径】" + jcodeProperties.getDiskPath()+jcodeProperties.getArtifact()); + result.append("【生成路径】" + jcodeProperties.getDiskPath() + "/" + jcodeProperties.getArtifact()); - for (String table:tables){ + for (String table : tables) { jcodeProperties.setTableName(table); ResultSet resultSet = getDbTables(jcodeProperties.getTableName()); while (resultSet.next()) { try { - parameter = new TemplateParameter(); parameter.setTableNameOriginal(resultSet.getString("TABLE_NAME")); parameter.setTableDescription(resultSet.getString("REMARKS")); parameter.setTableNameHump4Class(CamelHelper.underline2CamelClass(parameter.getTableNameOriginal())); parameter.setTableNameHump(CamelHelper.underlineToCamel(parameter.getTableNameOriginal())); - generateTemplate(parameter); } catch (Exception ex) { result.append("\n【" + parameter.getTableNameOriginal() + "】生成失败,原因:" + ex.getMessage()); @@ -79,6 +93,7 @@ public class CodeGenerateUtils { /** * 生成模板 + * * @param templateParameter * @throws Exception */ @@ -159,13 +174,13 @@ public class CodeGenerateUtils { private TemplateParameter fillTemplateParameter(TemplateParameter templateParameter) throws Exception { //获取表结构 ResultSet resultSet = getTablesColumns(templateParameter.getTableNameOriginal()); - templateParameter.setProjectDirctory(jcodeProperties.getDiskPath()+"/"+jcodeProperties.getArtifact()+"/"); - String url = String.format(DataBaseEnum.MYSQL.getUrl(), jcodeProperties.getDb().getIp(), jcodeProperties.getDb().getPort(), jcodeProperties.getDb().getDataBaseName()); + templateParameter.setProjectDirctory(jcodeProperties.getDiskPath() + "/" + jcodeProperties.getArtifact() + "/"); + String url = String.format(DataBaseEnum.MYSQL.getUrl(), jcodeProperties.getDb().getIp(), jcodeProperties.getDb().getDataBaseName()); templateParameter.setDbUrl(url); templateParameter.setDbUserName(jcodeProperties.getDb().getUser()); templateParameter.setDbPassword(jcodeProperties.getDb().getPassword()); templateParameter.setAuthor(jcodeProperties.getAuthor()); - templateParameter.setPackageName(jcodeProperties.getGroup()+"."+jcodeProperties.getArtifact().replace("-","")); + templateParameter.setPackageName(jcodeProperties.getGroup() + "." + jcodeProperties.getArtifact().replace("-", "")); templateParameter.setGenerateDate((new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date())); templateParameter.setVersion(jcodeProperties.getVersion()); //字段集合 @@ -173,8 +188,8 @@ public class CodeGenerateUtils { //字段 TableColumn tableColumn = null; //依赖 - // List importRely = new ArrayList<>(); - Set importRely= new HashSet(); + // List importRely = new ArrayList<>(); + Set importRely = new HashSet(); while (resultSet.next()) { //表名称 templateParameter.setTableNameOriginal(resultSet.getString("TABLE_NAME")); @@ -186,8 +201,8 @@ public class CodeGenerateUtils { //字段类型 tableColumn.setColumnType(dbType2JavaType(resultSet.getString("TYPE_NAME"))); //引入依赖 - String rely=getImportRely(tableColumn.getColumnType()); - if(!ObjectUtils.isEmpty(rely)) { + String rely = getImportRely(tableColumn.getColumnType()); + if (!ObjectUtils.isEmpty(rely)) { importRely.add(rely); } //转换字段名称,如 sys_name 变成 SysName @@ -207,12 +222,13 @@ public class CodeGenerateUtils { /** * 生成模板文件 + * * @param templateParameter * @throws Exception */ private void generateFileByTemplate(TemplateParameter templateParameter) throws Exception { Template template = FreeMarkerTemplateUtils.getTemplate(templateParameter.getDirectoryEnum().getTemplate()); - String path = templateParameter.getProjectDirctory() + String.format(templateParameter.getDirectoryEnum().getPath(),templateParameter.getPackageName().replace('.','/')); + String path = templateParameter.getProjectDirctory() + String.format(templateParameter.getDirectoryEnum().getPath(), templateParameter.getPackageName().replace('.', '/')); File file = new File(path); if (!file.isDirectory()) { file.mkdirs(); @@ -318,7 +334,7 @@ public class CodeGenerateUtils { private Connection connection() throws MyBizException { try { Class.forName(DataBaseEnum.MYSQL.getDriver()); - String url = String.format(DataBaseEnum.MYSQL.getUrl(), jcodeProperties.getDb().getIp(), jcodeProperties.getDb().getPort(), jcodeProperties.getDb().getDataBaseName())+"&useInformationSchema=true&remarks=true"; + String url = String.format(DataBaseEnum.MYSQL.getUrl(), jcodeProperties.getDb().getIp(), jcodeProperties.getDb().getDataBaseName()) + "&useInformationSchema=true&remarks=true"; Connection connection = DriverManager.getConnection(url, jcodeProperties.getDb().getUser(), jcodeProperties.getDb().getPassword()); return connection; } catch (Exception ex) { diff --git a/src/main/java/autojcode/controller/IndexController.java b/src/main/java/autojcode/controller/IndexController.java new file mode 100644 index 0000000..435bfc0 --- /dev/null +++ b/src/main/java/autojcode/controller/IndexController.java @@ -0,0 +1,16 @@ +package autojcode.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +@Controller +public class IndexController { + + @RequestMapping(value = "/") + public ModelAndView index(ModelAndView modelAndView) { + modelAndView.setViewName("views/index"); +// modelAndView.addObject("userList", userList); + return modelAndView; + } +} \ No newline at end of file diff --git a/src/main/java/autojcode/JcodeController.java b/src/main/java/autojcode/controller/JcodeController.java similarity index 60% rename from src/main/java/autojcode/JcodeController.java rename to src/main/java/autojcode/controller/JcodeController.java index 220f2b8..24a7d4b 100644 --- a/src/main/java/autojcode/JcodeController.java +++ b/src/main/java/autojcode/controller/JcodeController.java @@ -1,4 +1,4 @@ -package autojcode; +package autojcode.controller; import autojcode.domain.JcodeProperties; import autojcode.domain.JsonResult; @@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.*; /** * Created by lizhenyu on 2018/8/14 */ -@Api(value = "自动生成代码",description = "自动生成代码") +@Api(value = "自动生成代码", description = "自动生成代码") @RestController public class JcodeController { @Autowired @@ -19,13 +19,22 @@ public class JcodeController { @ApiOperation(value = "自动生成代码", notes = "自动生成代码", position = 1) @PostMapping(value = "/autoJCode") - public JsonResult autoJcodeForDb(@RequestBody @ApiParam(name="jcodeProperties",value="生成参数",required=true) JcodeProperties jcodeProperties) { + public JsonResult autoJcodeForDb(@RequestBody @ApiParam(name = "jcodeProperties", value = "生成参数", required = true) JcodeProperties jcodeProperties) { try { - // 我是mast1 String path = codeGenerateUtils.autoJcodeForDb(jcodeProperties); return ResultUtil.success(path); } catch (MyBizException e) { return ResultUtil.error(e); } } + + @ApiOperation(value = "自动生成代码", notes = "自动生成代码", position = 1) + @PostMapping(value = "/dbTest") + public JsonResult dbTest(@RequestBody JcodeProperties properties) { + try { + return ResultUtil.success(codeGenerateUtils.getDbTest(properties)); + } catch (Exception e) { + return ResultUtil.error(e); + } + } } diff --git a/src/main/java/autojcode/domain/ResultUtil.java b/src/main/java/autojcode/domain/ResultUtil.java index d7d5a19..2356f26 100644 --- a/src/main/java/autojcode/domain/ResultUtil.java +++ b/src/main/java/autojcode/domain/ResultUtil.java @@ -53,4 +53,12 @@ public class ResultUtil { return result; } + public static JsonResult error(Exception e){ + JsonResult result = new JsonResult(); + result.setCode(-1); + result.setMessage("系统错误"); + result.setData(null); + return result; + } + } diff --git a/src/main/java/autojcode/enums/DataBaseEnum.java b/src/main/java/autojcode/enums/DataBaseEnum.java index c996019..56e1495 100644 --- a/src/main/java/autojcode/enums/DataBaseEnum.java +++ b/src/main/java/autojcode/enums/DataBaseEnum.java @@ -4,7 +4,7 @@ package autojcode.enums; * 数据库枚举 */ public enum DataBaseEnum { - MYSQL("MYSQL","com.mysql.cj.jdbc.Driver","jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=UTF-8"); + MYSQL("MYSQL","com.mysql.cj.jdbc.Driver","jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=utf8&useSSL=false"); //ORACLE("ORACLE","oracle.jdbc.driver.OracleDriver","","DTO.java"); /** diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 4252c8f..4a6bc1b 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,5 +1,12 @@ spring: application: name: jcode-generation + freemarker: + template-loader-path: classpath:/templates + cache: false + charset: utf-8 + check-template-location: true + content-type: text/html + suffix: .ftl server: - port: 9090 + port: 9090 \ No newline at end of file diff --git a/src/main/resources/static/css/index.css b/src/main/resources/static/css/index.css new file mode 100644 index 0000000..ea3d8d3 --- /dev/null +++ b/src/main/resources/static/css/index.css @@ -0,0 +1,5 @@ +h2{color:red} + +.show-grid { + margin-bottom: 15px; +} \ No newline at end of file diff --git a/src/main/resources/static/js/index.js b/src/main/resources/static/js/index.js new file mode 100644 index 0000000..9187bca --- /dev/null +++ b/src/main/resources/static/js/index.js @@ -0,0 +1,110 @@ +$(function () { + + //读取配置 + readConf(); + $("#jcodeAction").click(function () { + if (validate()==false) { + alert("请输入必填项"); + return; + } + $("#jcodeAction").prop("disabled", "disabled"); + $.ajax({ + type: "post", + dataType: "json", + url: "/autoJCode?t=" + new Date().getTime(), + contentType: "application/json;charset=UTF-8",//指定消息请求类型 + data: JSON.stringify(buildJson()),//将js对象转成json对象 + success: function (data) { + console.log(data); + if (data.message == "success") { + alert(data.data) + } + $("#jcodeAction").removeAttr("disabled"); + }, error: function () { + alert("生成失败,异常"); + $("#jcodeAction").removeAttr("disabled"); + } + }); + }) + $("#saveConfig").click(function () { + saveConf(); + }) +}) + +function validate() { + if (getEmpty("group")||getEmpty("artifact")||getEmpty("address") || getEmpty("dbUser") || getEmpty("dbPassword")) { + return false; + } + return true; +} + +function buildJson() { + var json = { + "group": getVal("group"), + "artifact": getVal("artifact"), + "author": getVal("author"), + "version": getVal("version"), + "db": { + "ip": getVal("address").replace(':', ':'), + "dataBaseName": getVal("dataBaseName"), + "user": getVal("dbUser"), + "password": getVal("dbPassword") + }, + "diskPath": getVal("localPath"), + "tableName": "" + } + return json; +} + +function setForm(json) { + var val = JSON.parse(json) + setVal("group", val.group); + setVal("artifact", val.artifact); + setVal("author", val.author); + setVal("version", val.version); + setVal("address", val.db.ip); + setVal("dataBaseName", val.db.dataBaseName); + setVal("dbUser", val.db.user); + setVal("password", val.db.password); + setVal("diskPath", val.diskPath); +} + +function getVal(id) { + return $("#" + id).val().trim(); +} + +function getEmpty(id) { + return $("#" + id).val().trim() == ''; +} + +function setVal(id, value) { + return $("#" + id).val(value); +} + +function saveConf() { + var key = $('#confName').val().trim(); + if (key == '') { + return; + } + localStorage.setItem(key, JSON.stringify(buildJson())); + location.reload(); +} + +function readConf() { + var storage = window.localStorage; + var menu = ''; + for (var i = 0, len = storage.length; i < len; i++) { + var key = storage.key(i); + menu += '
  • ' + key + '
  • '; + } + $('#savedConf').append(menu); +} + +function writeconf(ob) { + var index = $(ob).index(); + var key = $(ob).eq(index).text(); + var value = localStorage.getItem(key); + if (value != null) { + setForm(value); + } +} \ No newline at end of file diff --git a/src/main/resources/templates/MapperProvider.ftl b/src/main/resources/templates/MapperProvider.ftl index 3932d07..c7f80bb 100644 --- a/src/main/resources/templates/MapperProvider.ftl +++ b/src/main/resources/templates/MapperProvider.ftl @@ -18,7 +18,7 @@ public class ${tableNameHump4Class}Provider { * @return */ public String find${tableNameHump4Class}List(@Param("${tableNameHump}") ${tableNameHump4Class} ${tableNameHump}) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(" select * from `${tableNameOriginal}` where 1=1 "); <#if tableColumnList?exists> <#list tableColumnList as model> @@ -44,7 +44,7 @@ public class ${tableNameHump4Class}Provider { * @return */ public String update${tableNameHump4Class}(@Param("${tableNameHump}") ${tableNameHump4Class} ${tableNameHump}) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(" update `${tableNameOriginal}` set "); <#if tableColumnList?exists> <#list tableColumnList as model> diff --git a/src/main/resources/templates/views/index.ftl b/src/main/resources/templates/views/index.ftl new file mode 100644 index 0000000..8ebb612 --- /dev/null +++ b/src/main/resources/templates/views/index.ftl @@ -0,0 +1,141 @@ + + + + Java+Vue前后端分离-工程自动生成神器 + + + + + + + + + + +
    +
    +
    +
    +
    +

    配置

    +

    +
    + +
    +
    +
    +
    +
    + +
    +
    +

    项目

    +

    +
    +
    +
    +
    + group + +
    +
    +
    +
    + artifact + +
    +
    +
    +
    +
    +
    + author + +
    +
    +
    +
    + version + +
    +
    +
    +
    +
    +

    数据库

    +

    +
    +
    +
    +
    + 地址 + +
    +
    +
    +
    + 数据库 + +
    +
    +
    +
    +
    +
    + user + +
    +
    +
    +
    + password + +
    +
    +
    +
    +
    +
    + 本地位置 + +
    +
    +
    +
    +
    +

    操作

    +

    +
    +
    +
    +
    + +
    +
    +
    +
    + + 保存配置 +
    +
    +
    +
    +
    +
    + + + \ No newline at end of file -- Gitee