mybatis-plus的代码生成器
简介:构建自定义mybatis-plus模板,自动生成mybatis,entity,mapper,service,controller
项目源码:https://github.com/y369q369/springBoot.git -> myBatisPlus
私聊QQ: 1486866853
1.demo完整代码结构

2.pom.xml依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <groupId>com.demo</groupId>
<artifactId>mybatisPlus</artifactId>
<version>0.0.-SNAPSHOT</version>
<name>mybatisPlus</name>
<description>使用mybatisPlus代码生成器</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.</version>
</dependency> <!-- web依赖,包含servlet,内置tomcat等 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency> <!-- ORACLE相关 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.0.1-atlassian-hosted</version>
</dependency> <!-- mybatis-plus依赖, 可以代替mybatis -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.</version>
</dependency> <!-- MyBatis-Plus 从 3.0. 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.</version>
</dependency> <!-- Freemarker模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
pom.xml
3.生成器代码
package mybatisPlus.generate; import java.util.ArrayList;
import java.util.List; import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; /**
* @author GrassPrince
* @Da2019年4月28日 2019年4月28日 - 下午2:37:11
* @Description 数据库对应代码生成器
*/
public class DataSourcesGenerator { public static void main(String[] args) {
// 生成地址 : // System.getProperty("user.dir") == 得到当前项目的实际地址
String outputDir = System.getProperty("user.dir") + "/src/main/java";
// String outputDir = "C://Users/VULCAN/Desktop/new";
// 表名, 注意大小写
String[] tableNames = new String[]{"test_hobby"};
// 数据源: 1-mysql 2-oracle
Integer dbType = ;
// 数据库地址
String url = "jdbc:mysql://localhost:3306/xl?useUnicode=true&characterEncoding=utf8";
// 用户名
String userName = "root";
// 密码
String password = "ok";
// 父包路径
String parentPackage = "mybatisPlus";
// 需要去掉的表名前缀
String prefixTable = "Test_";
generate(outputDir, tableNames, dbType, url, userName, password, parentPackage, prefixTable);
} /**
* @param outputDir 生成地址
* @param tableNames 表名
* @param dbType 数据源: 1-mysql 2-oracle
* @param url 数据库地址
* @param userName 用户名
* @param password 密码
* @param parentPackage 父包路径
* @param prefixTable 需要去掉的表名前缀
*/
public static void generate(String outputDir, String[] tableNames, Integer dbType, String url, String userName,
String password, String parentPackage, String prefixTable) {
// =============== 全局配置 ==================
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(outputDir)
.setActiveRecord(true) // 是否支持 AR, 实体类只需继承 Model 类即可进行强大的 CRUD 操作
.setAuthor("GrassPrince") // 设置作者名字
.setFileOverride(true) // 文件覆盖(全新文件)
.setIdType(IdType.AUTO) // 主键策略
.setEnableCache(false) // SQL 二级缓存
.setBaseResultMap(true) // SQL 映射文件
.setBaseColumnList(true) // SQL 片段
.setServiceName("%sService") // service的名字
.setOpen(false); // ================= 数据源配置 ===============
DataSourceConfig dsc = new DataSourceConfig();
if(dbType == ) {
dsc.setDbType(DbType.MYSQL)
.setDriverName("com.mysql.cj.jdbc.Driver");
}else if(dbType == ){
dsc.setDbType(DbType.ORACLE)
.setDriverName("oracle.jdbc.driver.OracleDriver");
}
dsc.setUrl(url)
.setUsername(userName)
.setPassword(password); // ================= 包配置 ===================
PackageConfig pc = new PackageConfig();
pc.setParent(parentPackage) // 配置父包路径
// .setModuleName("base") // 配置业务包路径
.setMapper("mapper")
.setEntity("entity")
.setService("service")
//.setServiceImpl("service.impl"); // 会自动生成 impl,可以不设定
.setController("controller"); // ================== 自定义配置 =================
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/ftl/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return System.getProperty("user.dir") + "/src/main/resources/mybatis/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList); // =================== 策略配置 ==================
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel) // 表名命名: underline_to_camel 底线变驼峰
.setColumnNaming(NamingStrategy.underline_to_camel) // 字段命名: underline_to_camel 底线变驼峰
.setInclude(tableNames) // 需要生成的 表名
.setCapitalMode(true) // 全局大写命名 ORACLE 注意
.setTablePrefix(prefixTable) // 去掉 表的前缀
// .setFieldPrefix(pc.getModuleName() + "_") // 去掉字段前缀
// .setSuperEntityClass("com.maoxs.pojo") // 继承类
// .setSuperControllerClass("com.maoxs.controller") // 继承类
// .setSuperEntityColumns("id") // 设置超级超级列
// .setEntityLombokModel(true) // 是否加入lombok
.setControllerMappingHyphenStyle(true); // 设置controller映射联字符 // ================== 自定义模板配置: 默认配置位置 mybatis-plus/src/main/resources/templates ======================
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
TemplateConfig tc = new TemplateConfig();
tc.setXml(null) // 设置生成xml的模板
.setEntity("/templates/ftl/entity.java") // 设置生成entity的模板
.setMapper("/templates/ftl/mapper.java") // 设置生成mapper的模板
.setController("/templates/ftl/controller.java") // 设置生成service的模板
.setService("/templates/ftl/service.java") // 设置生成serviceImpl的模板
.setServiceImpl("/templates/ftl/serviceImpl.java"); // 设置生成controller的模板 // ==================== 生成配置 ===================
AutoGenerator mpg = new AutoGenerator();
mpg.setCfg(cfg)
.setTemplate(tc)
.setGlobalConfig(gc)
.setDataSource(dsc)
.setPackageInfo(pc)
.setStrategy(strategy)
.setTemplateEngine(new FreemarkerTemplateEngine()); // 选择 freemarker引擎,注意 pom 依赖必须有!
mpg.execute();
} }
generate
4.自定义ftl生成器配置文件
package ${package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import ${package.Service}.${table.serviceName};
@Controller
@RequestMapping("/${table.entityPath}")
public class ${table.controllerName} {
    @Autowired
    private ${table.serviceName} ${table.entityPath}Service;
}
controller
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class ${table.serviceImplName} implements ${table.serviceName} {
    @Autowired
    private ${table.mapperName} ${table.entityPath}Mapper;
}
serviceImpl
package ${package.Service};
import ${package.Entity}.${entity};
public interface ${table.serviceName}{
}
service
package ${package.Entity};
import java.io.Serializable;
<#list table.importPackages as pkg>
<#if pkg == "java.util.Date">
import ${pkg};
</#if>
</#list>
/**
 * ${table.name} : ${table.comment!}
 */
public class ${entity}  implements Serializable {
    private static final long serialVersionUID = 1L;
<#-- ----------  属性私有化  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>
    <#if field.keyFlag>
    <#-- 主键 -->
    /**
     * 主键 : ${field.name},  ${field.comment!}
     */
    <#-- 普通字段 -->
    <#elseif field.convert>
    /**
     * ${field.name},  ${field.comment!}
     */
    </#if>
<#-- 乐观锁注解 -->
    <#if (versionFieldName!"") == field.name>
    @Version
    </#if>
<#-- 逻辑删除注解 -->
    <#if (logicDeleteFieldName!"") == field.name>
    @TableLogic
    </#if>
    private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  构造函数   ----------- -->
    public ${entity}(<#list table.fields as field>${field.propertyType} ${field.propertyName}<#sep>,</#list>){
        <#list table.fields as field>
            this.${field.propertyName} = ${field.propertyName};
        </#list>
    }
    public ${entity}(){
    }
<#------------  getter.setter封装  ---------->
<#if !entityLombokModel>
    <#list table.fields as field>
        <#if field.propertyType == "boolean">
            <#assign getprefix="is"/>
        <#else>
            <#assign getprefix="get"/>
        </#if>
    public ${field.propertyType} ${getprefix}${field.capitalName}() {
        return ${field.propertyName};
    }
        <#if entityBuilderModel>
    public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        <#else>
    public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        </#if>
        this.${field.propertyName} = ${field.propertyName};
        <#if entityBuilderModel>
        return this;
        </#if>
    }
    </#list>
</#if>
<#-------------  重写toString()  ----------------->
<#if !entityLombokModel>
    @Override
    public String toString() {
        return "${entity}{" +
    <#list table.fields as field>
        <#if field_index==0>
        "${field.propertyName}=" + ${field.propertyName} +
        <#else>
        ", ${field.propertyName}=" + ${field.propertyName} +
        </#if>
    </#list>
        "}";
    }
</#if>
}
entity
package ${package.Mapper};
import ${package.Entity}.${entity};
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ${table.mapperName}{
     /**
      *  查询表${table.name}所有信息
      */
     List<${entity}> find${entity}();
    <#list table.fields as field>
    <#if field.keyFlag>
     /**
      *  根据主键${field.propertyName}查询表${table.name}信息
      */
     ${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
    </#if>
    </#list>
    <#list table.fields as field>
    <#if field.keyFlag>
     /**
      *  根据主键${field.propertyName}查询表${table.name}信息
      */
     Integer delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
    </#if>
    </#list>
    <#list table.fields as field>
    <#if field.keyFlag>
     /**
      *  根据主键${field.propertyName}更新表${table.name}信息
      */
     Integer update${entity}By${field.propertyName}(${entity} ${table.entityPath});
    </#if>
    </#list>
    <#list table.fields as field>
    <#if field.keyFlag>
     /**
      *  新增表${table.name}信息
      */
     Integer add${entity}(${entity} ${table.entityPath});
    </#if>
    </#list>
}
mapper.java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}"> <#if enableCache>
<!-- 开启二级缓存 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> </#if>
<#if baseResultMap>
<!-- 通用查询映射结果 -->
<resultMap id="${entity}Map" type="${package.Entity}.${entity}">
<#list table.fields as field>
<#if field.keyFlag><#--生成主键排在第一位-->
<id column="${field.name}" property="${field.propertyName}" />
</#if>
</#list>
<#list table.commonFields as field><#--生成公共字段 -->
<result column="${field.name}" property="${field.propertyName}" />
</#list>
<#list table.fields as field>
<#if !field.keyFlag><#--生成普通字段 -->
<result column="${field.name}" property="${field.propertyName}" />
</#if>
</#list>
</resultMap> </#if> <!-- 查询表${table.name}所有信息 -->
<select id="find${entity}" resultMap="${entity}Map">
select * from ${table.name}
</select> <#list table.fields as field>
<#if field.keyFlag>
<!-- 根据主键${field.propertyName}查询表${table.name}信息 -->
<select id="find${entity}By${field.propertyName}" resultMap="${entity}Map">
select * from ${table.name} where ${field.name}=${r"#{"}${field.propertyName}${r"}"}
</select>
</#if>
</#list> <#list table.fields as field>
<#if field.keyFlag>
<!-- 根据主键${field.propertyName}删除表${table.name}信息 -->
<delete id="delete${entity}By${field.propertyName}">
delete from ${table.name} where ${field.name}=${r"#{"}${field.propertyName}${r"}"}
</delete>
</#if>
</#list> <#list table.fields as field>
<#if field.keyFlag>
<!-- 根据主键${field.propertyName}更新表${table.name}信息 -->
<update id="update${entity}By${field.propertyName}" parameterType="${package.Entity}.${entity}">
update from ${table.name} set
<#list table.fields as field><#if !field.keyFlag>${field.name}=${r"#{"}${field.propertyName}${r"}"}<#sep>,</#if></#list>
where <#list table.fields as field><#if field.keyFlag>${field.name}=${r"#{"}${field.propertyName}${r"}"}</#if></#list>
</update>
</#if>
</#list> <#list table.fields as field>
<#if field.keyFlag>
<!-- 新增表${table.name}信息 -->
<insert id="add${entity}">
insert into ${table.name}
(<#list table.fields as field><#if field.keyFlag>${field.name}</#if></#list><#list table.fields as field><#if !field.keyFlag>,${field.name}</#if></#list>)
values
(<#list table.fields as field><#if field.keyFlag>${r"#{"}${field.propertyName}${r"}"}</#if></#list><#list table.fields as field><#if !field.keyFlag>,${r"#{"}${field.propertyName}${r"}"}</#if></#list>)
</insert>
</#if>
</#list> <#if baseColumnList>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
<#list table.commonFields as field>
${field.name},
</#list>
${table.fieldNames}
</sql> </#if>
</mapper>
mapper.xml
5.全部配置完,直接用java Application运行generate
注意点:主要在generate中,把需要的地址,数据源,路径配置好即可使用
mybatis-plus的代码生成器的更多相关文章
- MyBatis Generator 详解
		
MyBatis Generator中文文档 MyBatis Generator中文文档地址:http://mbg.cndocs.tk/ 该中文文档由于尽可能和原文内容一致,所以有些地方如果不熟悉,看中 ...
 - MyBatis Generator 详解 【转来纯为备忘】
		
版权声明:版权归博主所有,转载请带上本文链接!联系方式:abel533@gmail.com 目录(?)[+] MyBatis Generator中文文档 运行MyBatis Generator X ...
 - mybatis  Generator配置文件详解
		
这里按照配置的顺序对配置逐个讲解,更细的内容可以配合中文文档参照. 1. 配置文件头 <?xml version="1.0" encoding="UTF-8&quo ...
 - 转载:mybatis自动生成
		
MyBatis Generator中文文档 MyBatis Generator中文文档地址: http://generator.sturgeon.mopaas.com/ 该中文文档由于尽可能和原文内容 ...
 - MyBatis Generator中文文档
		
MyBatis Generator中文文档 MyBatis Generator中文文档地址: http://mbg.cndocs.tk/ 该中文文档由于尽可能和原文内容一致,所以有些地方如果不熟悉,看 ...
 - MyBatis Generator 详解(转)
		
MyBatis Generator中文文档 MyBatis Generator中文文档地址:http://mbg.cndocs.tk/ 该中文文档由于尽可能和原文内容一致,所以有些地方如果不熟悉,看中 ...
 - Java代码生成器CodeX4J介绍
		
用代码生成器生成一些固定的或有规律的代码,可以有效的提高工作效率.我写了个开源的,放在了GitHub上,希望能对有需要的朋友有所帮助. GitHub代码地址https://github.com/jac ...
 - MyBatis Geneator详解<转>
		
MyBatis Geneator中文文档地址: http://generator.sturgeon.mopaas.com/ 该中文文档由于尽可能和原文内容一致,所以有些地方如果不熟悉,看中文版的文档的 ...
 - MyBatis Generator 详解  专题
		
idea中有plugin可提高效率: http://www.henryxi.com/use-idea-mybatis-plugin-generate-mapper-files eg: <?xml ...
 - java web开发入门十一(idea maven mybatis自动代码生成)基于intellig idea
		
6.idea maven mybatis逆向工程(代码生成器) 1.配置pom.xml 在plugins标签下添加mybatis-generator-maven-plugin <plugin&g ...
 
随机推荐
- Flask-----Flask里引用哈希密码
			
哈希密码(Password Hash): 对口令进行一次性的加密处理而形成的杂乱字符串.这个加密的过程被认为是不可逆的,也就是说,人们认为从哈希串中是不可能还原出原口令的.(这句话是比较官方的解释). ...
 - 双网卡绑定一个IP--bond
			
双网卡绑定一个IP 步骤1:新建/etc/sysconfig/network-scripts/ifcfg-bond0文件 DEVICE=bond0 ONBOOT=yes BOOTPROTO=stati ...
 - 2018上C语言程序设计(初级)作业- 第2次作业
			
一.预习作业 在课前或者课后观看浙江大学程序设计入门-C语言课程中第2周.第3周的判断部分和第4周的判断部分. 二.PTA作业 完成第7周.第8周和第9周和第10周共8次pta作业,将PTA作业中部分 ...
 - Linux恢复误删除的文件或者目录(转)
			
linux不像windows有个回收站,使用rm -rf *基本上文件是找不回来的. 那么问题来了: 对于linux下误删的文件,我们是否真的无法通过软件进行恢复呢? 答案当然是否定的,对于误删的文件 ...
 - 个人 git-hub使用方法
			
注册码云 安装git hub git init here 创建本地仓库(repository),将会在文件夹下创建一个 .git 文件夹,.git 文件夹里存储了所有的版本信息.标记等 ...
 - Privoxy代理的使用
			
目录 1. Privoxy介绍 1.1 安装 1.2 配置 1.3 使用 1.4 其他配置 1.5 测试链接及查看配置 2. 相关信息 https://www.privoxy.org/ http:// ...
 - install MariaDB 10.2 on Ubuntu 18
			
Here are the commands to run to install MariaDB 10.2 from the MariaDB repository on your Ubuntu syst ...
 - 2018-2019-2 20165313 《网络对抗技术》Exp4 恶意代码分析
			
一.实践目标 1.监控你自己系统的运行状态,看有没有可疑的程序在运行. 2.分析一个恶意软件,就分析Exp2或Exp3中生成后门软件:分析工具尽量使用原生指令或sysinternals,systrac ...
 - ConcurrentDictionary对象
			
ConcurrentDictionary<int, List<a>> dic = new ConcurrentDictionary<int, List<a>& ...
 - 听说https更安全
			
0--介绍: 现在人们对网络的依赖越来越重,那么对于网络安全的要求也越来越高,传统的http协议实现了网络中的快速传输,完整传输,保证了信息的完整性,但是对于网络的安全性却没有那么强,很容易被人劫持, ...