https://gitee.com/baomidou/mybatis-plus-samples/tree/master/mybatis-plus-sample-generator 官方例子
方式一、
1.pom.xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.0-beta</version>
</dependency>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>//版本需要自己对应自己的mysql版本,我的 8.0.15 -- cmd执行:mysql -uroot -p123456
<configuration>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
2.新建generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="application.yml" />
<!-- mysql驱动的位置 这个是MySQL连接的jar包,你需要指定你自己计算机上的jar包的位置-->
<classPathEntry location="C:\Users\hfyx0\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar" />
<context id="Tables" targetRuntime="MyBatis3">
<!-- 注释 -->
<commentGenerator>
<!-- 是否生成注释代时间戳 -->
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- JDBC连接 其中connectionURL后面的newtest改为你创建的数据库,紧跟在后面是数据库连接的账户和密码-->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/kry"
userId="root"
password="123456">
</jdbcConnection>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成实体类地址 这里需要你改动,其中targetPackage需要根据你自己创建的目录进行改动 -->
<javaModelGenerator targetPackage="com.example.springbootmybatisgeneratortest.pojo" targetProject="src/main/java">
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaModelGenerator>
<!-- 生成mapper xml文件 这里不需要改动 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapper xml对应Client 这里需要改动targetPackage,依据你自己的工程-->
<javaClientGenerator targetPackage="com.example.springbootmybatisgeneratortest.mapper" targetProject="src/main/java" type="XMLMAPPER">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 配置表信息 -->
<!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample
是否生成 example类 -->
<table schema="kry" tableName="sys_user"
domainObjectName="SysUser" enableCountByExample="true"
enableDeleteByExample="true" enableSelectByExample="true"
enableUpdateByExample="true">
</table>
<!-- <table schema="kry" tableName="product"
domainObjectName="Product" enableCountByExample="true"
enableDeleteByExample="true" enableSelectByExample="true"
enableUpdateByExample="true">
</table>-->
</context>
</generatorConfiguration>
3.执行
方式一:
方式二:
mybatis-generator:generate -e
4.成功之后代码:
方式二、
pom.xml
maven方式1
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.0-beta</version>
</dependency>
maven方式2
注意:mybatis-plus-boot-starter中移除了自动生成代码功能,需要手动添加mybatis-plus-generator,
但是在3.3.2版本中没有freemaker,需要再加freemarker
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!--plus 自动生成代码start-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
<scope>compile</scope>
</dependency>
package com.kry.xr.util;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MybatisPlusGeneratorUtil {
/* <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.0-beta</version>
</dependency>*/
// 全局配置
private final static String OUTPUT_DIR = "/src/main/java";// 生成文件的输出目录
private final static String AUTHOR = "kry";// 开发人员
private final static String PARENT = "com.kry";// 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
private final static String MODULE_NAME = "xr";// 父包模块名
/**
* <p>读取控制台内容</p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
/**
* RUN THIS
*/
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + OUTPUT_DIR);
gc.setAuthor(AUTHOR);
gc.setOpen(false);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/blog?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");// JDK7
//dsc.setDriverName("com.mysql.cj.jdbc.Driver");// JDK8
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setModuleName(MODULE_NAME);
pc.setParent(PARENT);
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
//自定义模板,生成自己想要的各种方法(如果没有就使用mybatis-plus自带的模板)
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + OUTPUT_DIR + "/" + PARENT.replaceAll("\\.", "/") + "/"
+ MODULE_NAME + "/mapper/" + tableInfo.getEntityName() + "Mapper.xml" ;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("com.kry.xr.BaseEntity");
strategy.setEntityLombokModel(true);//【实体】是否为lombok模型
// strategy.setSuperControllerClass("com.kry.xr.BaseController");
strategy.setSuperServiceClass("com.kry.xr.base.BaseService");
strategy.setSuperServiceImplClass("com.kry.xr.base.service.BaseServiceimpl");
strategy.setSuperMapperClass("com.kry.xr.base.IBaseMapper");
//继承的类,生成类文建 public interface PressMapper extends BaseMapper<Press> {}
strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
//strategy.setInclude(scanner("表名"));
strategy.setInclude("t_user","t_press");
strategy.setInclude("t_user");
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
//生成类名去除表前缀
strategy.setTablePrefix( "t_");
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
System.out.println("生成成功!");
}
}
自定义ftl模板
mapper.xml.ftl
<?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="BaseResultMap" 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>
<#if baseColumnList>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
<#list table.commonFields as field>
${field.name},
</#list>
${table.fieldNames}
</sql>
</#if>
<#if baseColumnList>
<!-- 查询列表 -->
<select id="selectList" parameterType="string" resultMap="BaseResultMap">
select
<#list table.commonFields as field>
${field.name},
</#list>
${table.fieldNames}
from ${table.name}
<where>
<#list table.fields as field>
<if test="${field.propertyName} != null">
and ${field.name} = ${r"#{"}${field.propertyName}${r"}"}
</if>
</#list>
</where>
</select>
</#if>
<#if baseColumnList>
<!-- 新增 -->
<insert id="insert" parameterType="${package.Entity}.${entity}">
insert into ${table.name}
( ${table.fieldNames})
values
(
<#list table.fields as field>
${r"#{"}${field.propertyName}${r"}"}
</#list>
)
</insert>
</#if>
<update id="update" parameterType="${package.Entity}.${entity}">
update ${table.name}
<set>
<#list table.fields as field>
<if test="${field.propertyName} != null">
${field.name} = ${r"#{"}${field.propertyName}${r"}"},
</if>
</#list>
</set>
<where>
<#list table.commonFields as field>
<#if field.keyFlag><#--主键id位-->
${field.name}=${r"#{"}${field.propertyName}${r"}"}
</#if>
</#list>
</where>
</update>
<delete id="deleteById" parameterType="${package.Entity}.${entity}">
delete from ${table.name}
<where>
<#list table.commonFields as field>
<#if field.keyFlag><#--主键id位-->
and ${field.name}=${r"#{"}${field.propertyName}${r"}"}
</#if>
</#list>
<#list table.fields as field>
<if test="${field.propertyName} != null">
and ${field.name} = ${r"#{"}${field.propertyName}${r"}"}
</if>
</#list>
</where>
</delete>
</mapper>
controller.java.ftl
package ${package.Controller};
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.kry.xr.service.${table.serviceName};
import com.kry.xr.entity.${entity};
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* <p>
* ${table.comment!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
* @version v1.0
*/
<#if restControllerStyle>
@Api(tags = {"${table.comment!}"})
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first};
/**
* 查询分页数据
*/
@ApiOperation(value = "查询分页数据")
@RequestMapping(value = "/list")
public String findListByPage(@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,@RequestParam(name = "pageSize", defaultValue = "20") int pageSize){
return null;
}
/**
* 根据id查询
* @author ${author}
* @since ${date}
*/
@ApiOperation(value = "根据id查询数据")
@RequestMapping(value = "/getById")
public String getById(@RequestParam("pkid") String pkid){
return null;
}
/**
* 新增
* @author ${author}
* @since ${date}
*/
@ApiOperation(value = "新增数据")
@RequestMapping(value = "/insert", method = RequestMethod.POST)
public String insert(@RequestBody ${entity} ${entity?uncap_first}){
return null;
}
/**
* 删除
* @author ${author}
* @since ${date}
*/
@ApiOperation(value = "删除数据")
@RequestMapping(value = "/del")
public String delete(@RequestParam("ids") List<String> ids){
return null;
}
/**
* 修改
* @author ${author}
* @since ${date}
*/
@ApiOperation(value = "更新数据")
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@RequestBody ${entity} ${entity?uncap_first}){
return null;
}
}
</#if>