-
认真是一种态度,坚持是一种品格,优秀是一种习惯!
掰着手指头算算,从15年毕业到现在,已经是工作的第四个年头了。都说程序猿3年是个坎,我也不知道算是个坎还是不是坎。反正工作还在继续,学习不能停止。越工作越觉得自己啥也不会<><ganga .....扯远了,说回正题。
自打用了Mybatis-Plus觉得开发快了不止一星半点。但是每次新增一个业务时总要从bean到mapper再到service搞一遍总还是有些不爽的,还在mp有diamante生成器,简单记录一下这个代码生成器怎么玩。
1 基础框架
SpringBoot 2.0.6、JDK 1.8、mybatis-plus 3.1.1、mybatis-plus-generator 3.1.1、velocity 1.7、MySQL 5.7
因基本都称mybatis-plus为mp,后面我都简称mp
2.具体实现
- 创建项目我就不在描述了,学习第一天记录过了坚持学习第一天
- 因为mp 3.1.1版本把代码生成单独拎出来了,所以需要在原项目基础上加上generate相关包。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
因为代码生成的模板我这里选择用velocity,所以将velocity 包引入了。语法参考:https://jzhua.iteye.com/blog/311405
默认可以直接使用mp提供的默认模板文件。
这里先简单通过执行main方法的形式使用该代码生成器,mp的代码生成器很完善,基本上满足开发的基本需要。
基础表
create database demo_generate;
use demo_generate;
create table if not exists t_equipment (
equipment_id int(11) not null AUTO_INCREMENT comment '设备ID',
device_name varchar(50) comment '设备名称',
modnum varchar(50) comment '设备编号',
picture varchar(255) comment '设备图片',
create_time date comment '创建时间',
enabled tinyint(4) default 0 comment '1启用/0禁用',
primary key (equipment_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='设备信息';
先简单看一下执行效果:
"C:\Program Files\Java\jdk1.8.0_31\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1.1\lib\idea_rt.jar=62211:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\java\jdk1.8.0_31\jre\lib\charsets.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\deploy.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\access-bridge-64.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\cldrdata.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\dnsns.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\jaccess.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\jfxrt.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\localedata.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\nashorn.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\sunec.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\sunjce_provider.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\sunmscapi.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\sunpkcs11.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\ext\zipfs.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\javaws.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\jce.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\jfr.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\jfxswt.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\jsse.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\management-agent.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\plugin.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\resources.jar;C:\Program Files\java\jdk1.8.0_31\jre\lib\rt.jar;C:\workspaces\Java_learn\cooper_sp\target\classes;C:\software\apache-maven-3.5.0\repo\org\springframework\boot\spring-boot-starter-web\2.1.5.RELEASE\spring-boot-starter-web-2.1.5.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\boot\spring-boot-starter\2.1.5.RELEASE\spring-boot-starter-2.1.5.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\boot\spring-boot\2.1.5.RELEASE\spring-boot-2.1.5.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\boot\spring-boot-starter-logging\2.1.5.RELEASE\spring-boot-starter-logging-2.1.5.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\software\apache-maven-3.5.0\repo\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\software\apache-maven-3.5.0\repo\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;C:\software\apache-maven-3.5.0\repo\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar;C:\software\apache-maven-3.5.0\repo\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;C:\software\apache-maven-3.5.0\repo\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;C:\software\apache-maven-3.5.0\repo\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\boot\spring-boot-starter-json\2.1.5.RELEASE\spring-boot-starter-json-2.1.5.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;C:\software\apache-maven-3.5.0\repo\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;C:\software\apache-maven-3.5.0\repo\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;C:\software\apache-maven-3.5.0\repo\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.8\jackson-datatype-jdk8-2.9.8.jar;C:\software\apache-maven-3.5.0\repo\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.8\jackson-datatype-jsr310-2.9.8.jar;C:\software\apache-maven-3.5.0\repo\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.8\jackson-module-parameter-names-2.9.8.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\boot\spring-boot-starter-tomcat\2.1.5.RELEASE\spring-boot-starter-tomcat-2.1.5.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\apache\tomcat\embed\tomcat-embed-core\9.0.19\tomcat-embed-core-9.0.19.jar;C:\software\apache-maven-3.5.0\repo\org\apache\tomcat\embed\tomcat-embed-el\9.0.19\tomcat-embed-el-9.0.19.jar;C:\software\apache-maven-3.5.0\repo\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.19\tomcat-embed-websocket-9.0.19.jar;C:\software\apache-maven-3.5.0\repo\org\hibernate\validator\hibernate-validator\6.0.16.Final\hibernate-validator-6.0.16.Final.jar;C:\software\apache-maven-3.5.0\repo\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;C:\software\apache-maven-3.5.0\repo\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\software\apache-maven-3.5.0\repo\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-web\5.1.7.RELEASE\spring-web-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-beans\5.1.7.RELEASE\spring-beans-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-webmvc\5.1.7.RELEASE\spring-webmvc-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-aop\5.1.7.RELEASE\spring-aop-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-context\5.1.7.RELEASE\spring-context-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-expression\5.1.7.RELEASE\spring-expression-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\com\h2database\h2\1.4.199\h2-1.4.199.jar;C:\software\apache-maven-3.5.0\repo\org\projectlombok\lombok\1.18.8\lombok-1.18.8.jar;C:\software\apache-maven-3.5.0\repo\com\baomidou\mybatis-plus-generator\3.1.1\mybatis-plus-generator-3.1.1.jar;C:\software\apache-maven-3.5.0\repo\com\baomidou\mybatis-plus-extension\3.1.1\mybatis-plus-extension-3.1.1.jar;C:\software\apache-maven-3.5.0\repo\com\baomidou\mybatis-plus-core\3.1.1\mybatis-plus-core-3.1.1.jar;C:\software\apache-maven-3.5.0\repo\com\baomidou\mybatis-plus-annotation\3.1.1\mybatis-plus-annotation-3.1.1.jar;C:\software\apache-maven-3.5.0\repo\com\github\jsqlparser\jsqlparser\1.2\jsqlparser-1.2.jar;C:\software\apache-maven-3.5.0\repo\org\mybatis\mybatis\3.5.1\mybatis-3.5.1.jar;C:\software\apache-maven-3.5.0\repo\org\mybatis\mybatis-spring\2.0.1\mybatis-spring-2.0.1.jar;C:\software\apache-maven-3.5.0\repo\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar;C:\software\apache-maven-3.5.0\repo\org\apache\velocity\velocity\1.7\velocity-1.7.jar;C:\software\apache-maven-3.5.0\repo\commons-collections\commons-collections\3.2.1\commons-collections-3.2.1.jar;C:\software\apache-maven-3.5.0\repo\commons-lang\commons-lang\2.4\commons-lang-2.4.jar;C:\software\apache-maven-3.5.0\repo\com\baomidou\mybatis-plus-boot-starter\3.1.1\mybatis-plus-boot-starter-3.1.1.jar;C:\software\apache-maven-3.5.0\repo\com\baomidou\mybatis-plus\3.1.1\mybatis-plus-3.1.1.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\boot\spring-boot-autoconfigure\2.1.5.RELEASE\spring-boot-autoconfigure-2.1.5.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\boot\spring-boot-starter-jdbc\2.1.5.RELEASE\spring-boot-starter-jdbc-2.1.5.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\com\zaxxer\HikariCP\3.2.0\HikariCP-3.2.0.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-jdbc\5.1.7.RELEASE\spring-jdbc-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-tx\5.1.7.RELEASE\spring-tx-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-core\5.1.7.RELEASE\spring-core-5.1.7.RELEASE.jar;C:\software\apache-maven-3.5.0\repo\org\springframework\spring-jcl\5.1.7.RELEASE\spring-jcl-5.1.7.RELEASE.jar" com.cooper.common.generate.AutoGenerateCode
14:58:43.195 [main] INFO com.cooper.common.generate.AutoGenerateCode - equipment
14:58:43.199 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...==========================
14:58:43.517 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\bean]
14:58:43.517 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\controller]
14:58:43.518 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\mapper\xml]
14:58:43.519 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\service]
14:58:43.519 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 创建目录: [C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\service\impl]
14:58:43.536 [main] DEBUG org.apache.velocity - CommonsLogLogChute name is 'org.apache.velocity'
14:58:43.536 [main] DEBUG org.apache.velocity - Initializing Velocity, Calling init()...
14:58:43.536 [main] DEBUG org.apache.velocity - Starting Apache Velocity v1.7 (compiled: 2010-11-19 12:14:37)
14:58:43.536 [main] DEBUG org.apache.velocity - Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties
14:58:43.536 [main] DEBUG org.apache.velocity - Trying to use logger class org.apache.velocity.runtime.log.AvalonLogChute
14:58:43.536 [main] DEBUG org.apache.velocity - Target log system for org.apache.velocity.runtime.log.AvalonLogChute is not available (java.lang.NoClassDefFoundError: org/apache/log/format/Formatter). Falling back to next log system...
14:58:43.536 [main] DEBUG org.apache.velocity - Trying to use logger class org.apache.velocity.runtime.log.Log4JLogChute
14:58:43.536 [main] DEBUG org.apache.velocity - Target log system for org.apache.velocity.runtime.log.Log4JLogChute is not available (java.lang.NoClassDefFoundError: org/apache/log4j/Layout). Falling back to next log system...
14:58:43.536 [main] DEBUG org.apache.velocity - Trying to use logger class org.apache.velocity.runtime.log.CommonsLogLogChute
14:58:43.536 [main] DEBUG org.apache.velocity - Using logger class org.apache.velocity.runtime.log.CommonsLogLogChute
14:58:43.540 [main] DEBUG org.apache.velocity - ResourceLoader instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
14:58:43.549 [main] DEBUG org.apache.velocity - ResourceCache: initialized (class org.apache.velocity.runtime.resource.ResourceCacheImpl) with class java.util.Collections$SynchronizedMap cache map.
14:58:43.550 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Stop
14:58:43.552 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Define
14:58:43.552 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Break
14:58:43.553 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Evaluate
14:58:43.554 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Literal
14:58:43.555 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Macro
14:58:43.556 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Parse
14:58:43.557 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Include
14:58:43.558 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach
14:58:43.587 [main] DEBUG org.apache.velocity - Created '20' parsers.
14:58:43.593 [main] DEBUG org.apache.velocity - Velocimacro : "velocimacro.library" is not set. Trying default library: VM_global_library.vm
14:58:43.594 [main] DEBUG org.apache.velocity - Could not load resource 'VM_global_library.vm' from ResourceLoader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader: ClasspathResourceLoader Error: cannot find resource VM_global_library.vm
14:58:43.594 [main] DEBUG org.apache.velocity - Velocimacro : Default library not found.
14:58:43.594 [main] DEBUG org.apache.velocity - Velocimacro : allowInline = true : VMs can be defined inline in templates
14:58:43.594 [main] DEBUG org.apache.velocity - Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions
14:58:43.594 [main] DEBUG org.apache.velocity - Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed.
14:58:43.594 [main] DEBUG org.apache.velocity - Velocimacro : autoload off : VM system will not automatically reload global library macros
14:58:43.624 [main] DEBUG org.apache.velocity - ResourceManager : found /templates/entity.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
14:58:43.635 [main] DEBUG org.apache.velocity - Left side (${versionFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 86, column 26]
14:58:43.635 [main] DEBUG org.apache.velocity - Left side (${logicDeleteFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 90, column 30]
14:58:43.635 [main] DEBUG org.apache.velocity - Left side (${versionFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 86, column 26]
14:58:43.635 [main] DEBUG org.apache.velocity - Left side (${logicDeleteFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 90, column 30]
14:58:43.635 [main] DEBUG org.apache.velocity - Left side (${versionFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 86, column 26]
14:58:43.635 [main] DEBUG org.apache.velocity - Left side (${logicDeleteFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 90, column 30]
14:58:43.636 [main] DEBUG org.apache.velocity - Left side (${versionFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 86, column 26]
14:58:43.636 [main] DEBUG org.apache.velocity - Left side (${logicDeleteFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 90, column 30]
14:58:43.636 [main] DEBUG org.apache.velocity - Left side (${versionFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 86, column 26]
14:58:43.636 [main] DEBUG org.apache.velocity - Left side (${logicDeleteFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 90, column 30]
14:58:43.638 [main] DEBUG org.apache.velocity - Left side (${versionFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 86, column 26]
14:58:43.638 [main] DEBUG org.apache.velocity - Left side (${logicDeleteFieldName}) of '==' operation has null value. If it is a reference, it may not be in the context or its toString() returned null. /templates/entity.java.vm[line 90, column 30]
14:58:43.643 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/entity.java.vm; 文件:C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\bean\TEquipment.java
14:58:43.644 [main] DEBUG org.apache.velocity - ResourceManager : found /templates/mapper.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
14:58:43.650 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/mapper.java.vm; 文件:C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\mapper\TEquipmentMapper.java
14:58:43.653 [main] DEBUG org.apache.velocity - ResourceManager : found /templates/mapper.xml.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
14:58:43.662 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/mapper.xml.vm; 文件:C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\mapper\xml\TEquipmentMapper.xml
14:58:43.664 [main] DEBUG org.apache.velocity - ResourceManager : found /templates/service.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
14:58:43.670 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/service.java.vm; 文件:C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\service\ITEquipmentService.java
14:58:43.672 [main] DEBUG org.apache.velocity - ResourceManager : found /templates/serviceImpl.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
14:58:43.678 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/serviceImpl.java.vm; 文件:C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\service\impl\TEquipmentServiceImpl.java
14:58:43.680 [main] DEBUG org.apache.velocity - ResourceManager : found /templates/controller.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
14:58:43.682 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/controller.java.vm; 文件:C:\workspaces\Java_learn\cooper_sp/src/main/java\com\cooper\module\equipment\controller\TEquipmentController.java
14:58:43.683 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!==========================
14:58:43.683 [main] ERROR com.cooper.common.generate.AutoGenerateCode - >>>>>>> Generate Code Completed... >>>>>>>
Process finished with exit code 0
通过执行日志,我们基本上能看到整个生成执行过程,先读取数据相关信息,将读取到信息通过流输出到模板,模板解析生成对应得bean,mapper等文件。
-
生成的代码:
生成结果
附上主要代码:
package com.cooper.common.generate;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
/**
* mp代码生成实践
*
* @author jackcooperz
* @version v1.0
* @since 2019
*/
@Component
public class AutoGenerateCode {
private static Logger logger = LogManager.getLogger(AutoGenerateCode.class);
public static void main(String[] args) {
/**
* 根路径,我这里先直接放到此项目中。可以根据自己需要修改制定
*/
String basePath = System.getProperty("user.dir");
String parentPackageName = "com.cooper.module";
String moduleName = "equipment";
String[] tableNames = new String[]{"t_equipment"};
String[] tablePres = new String[]{"f_"};
String jdbcHost = "localhost";
String jdbcPort = "3306";
String jdbcDatabase = "demo_generate";
String jdbcUrl = String.format("jdbc:mysql://%s:%s/%s?characterEncoding=utf8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai",
jdbcHost, jdbcPort, jdbcDatabase);
AutoDataSourceConfig autoDataSourceConfig = AutoDataSourceConfig.builder()
.jdbcDriverClassName("com.mysql.jdbc.Driver")
.jdbcPassword("admin123")
.jdbcUserName("admin")
.jdbcUrl(jdbcUrl)
.build();
String outputDir = String.format("%s/src/main/java", basePath);
new AutoGenerateCode().generateCode(outputDir, parentPackageName,
moduleName, autoDataSourceConfig, tablePres, tableNames);
}
/**
* 生成代码
*
* @param outputDir 输出目录
* @param parentPackageName 父级包
* @param moduleName 模块名称
* @param dataSourceConfig 数据源配置
* @param tablePres 表前缀
* @param tableNames 待生成表名
*/
private void generateCode(String outputDir, String parentPackageName,
String moduleName, AutoDataSourceConfig dataSourceConfig, String[] tablePres, String[] tableNames) {
try {
AutoGenerator autoGenerator = new AutoGenerator();
autoGenerator.setGlobalConfig(initGlobConfig(outputDir))
.setDataSource(initDataSource(dataSourceConfig))
.setStrategy(initStrategyConfig(tablePres, tableNames))
.setPackageInfo(initPackage(parentPackageName, moduleName))
.setTemplate(initTemplateConfig())
.execute();
logger.error(">>>>>>> Generate Code Completed... >>>>>>>");
} catch (Exception e) {
logger.error("Generate Code failed:", e);
throw new RuntimeException(String.format("Generate Code failed"));
}
}
/**
* 全局设置配置
*
* @param outputDir 生成文件输出根目录
* @return GlobalConfig
*/
private GlobalConfig initGlobConfig(String outputDir) {
return new GlobalConfig()
.setOutputDir(outputDir)
/**
* 方法都比较见名知意了,就不做赘述
*/
.setFileOverride(false)
.setOpen(false)
.setEnableCache(false)
.setKotlin(false)
.setActiveRecord(false)
.setBaseResultMap(true)
.setBaseColumnList(true)
/**
* 以下个人系统的类后缀,可根据自己需要调整
*/
.setMapperName("%sMapper")
.setXmlName("%sMapper")
.setServiceName("I%sService")
.setServiceImplName("%sServiceImpl")
.setControllerName("%sController")
.setAuthor("jackcooperz")
.setIdType(IdType.ID_WORKER);
}
/**
* 设置数据源信息
*
* @param dataSourceConfig 数据源配置
* @return DataSourceConfig
*/
private DataSourceConfig initDataSource(AutoDataSourceConfig dataSourceConfig) {
return new DataSourceConfig()
.setDbType(DbType.MYSQL)
.setTypeConvert(new MySqlTypeConvert() {
/**
* 自定义部分数据库类型对应转换的Java类型,根据个人需要设定
*/
@Override
public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
if (fieldType.toLowerCase().contains("tinyint")) {
return DbColumnType.BOOLEAN;
}
return super.processTypeConvert(globalConfig, fieldType);
}
})
.setDriverName(dataSourceConfig.getJdbcDriverClassName())
.setUrl(dataSourceConfig.getJdbcUrl())
.setUsername(dataSourceConfig.getJdbcUserName())
.setPassword(dataSourceConfig.getJdbcPassword());
}
/**
* 设置生成策略
*
* @param tablePre 表前缀
* @param tableNames 待生成表列表
* @return StrategyConfig
*/
private StrategyConfig initStrategyConfig(String[] tablePre, String[] tableNames) {
return new StrategyConfig()
.setNaming(NamingStrategy.underline_to_camel)
.setColumnNaming(NamingStrategy.underline_to_camel)
.setTablePrefix(tablePre)
.setControllerMappingHyphenStyle(true)
.setEntityTableFieldAnnotationEnable(true)
.setEntityLombokModel(true)
.setInclude(tableNames)
.setRestControllerStyle(false);
}
/**
* 设置包配置信息
*
* @param parentPackageName 父级包
* @param moduleName 模块名称
* @return PackageConfig
*/
private PackageConfig initPackage(String parentPackageName, String moduleName) {
logger.info(moduleName);
PackageConfig packageConfig = new PackageConfig()
.setParent(parentPackageName)
.setEntity("bean")
.setService("service")
.setServiceImpl("service.impl")
.setMapper("mapper")
.setXml("mapper.xml")
.setController("controller");
if (StringUtils.isNotEmpty(moduleName)) {
packageConfig.setModuleName(moduleName);
}
return packageConfig;
}
/**
* 指定生成代码模板文件路径【可以不指定,使用mp默认的】
*
* @return TemplateConfig
*/
private TemplateConfig initTemplateConfig() {
return new TemplateConfig();
/**
* 这里暂时不自定义模板,若有需要可自行修改
*/
// .setController("/templates/mybatis/controller.java.vm")
// .setService("/templates/mybatis/service.java.vm")
// .setEntity("/templates/mybatis/entity.java.vm")
// .setServiceImpl("/templates/mybatis/serviceImpl.java.vm")
// .setXml("/templates/mybatis/mapper.xml.vm")
// .setMapper("/templates/mybatis/mapper.java.vm");
}
}
- 数据源实体
package com.cooper.common.generate;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class AutoDataSourceConfig {
private String jdbcUrl;
private String jdbcDriverClassName;
private String jdbcUserName;
private String jdbcPassword;
}
网友评论