参考官网地址 https://baomidou.com/pages/981406/
快速开始
mybatis包
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
freemarker引擎模板
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
java代码
package com.unicom.sh.content;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import java.util.Collections;
@Slf4j
public class Demo {
public static void main(String[] args) {
StringBuffer projectPath = new StringBuffer();
String systemPath = System.getProperty("user.dir");
projectPath.append(systemPath.replaceAll("\\\\", "//")).append("//src//main");
System.out.println(projectPath);
FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/content?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai", "root", "123456")
.globalConfig(builder -> {
builder
.author("admin")
.enableSwagger()
.fileOverride()
.outputDir(projectPath + "//java");
})
.packageConfig(builder -> {
builder.parent("com.unicom.sh")
.moduleName("content")
.entity("domain.entity")
.controller("controller")
.other("other")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, projectPath + "//resources//mapper"));
})
.strategyConfig(builder -> {
builder.addInclude("ability_photo_202001");
})
.templateEngine(new FreemarkerTemplateEngine())
.execute();
}
}
自定义模板
1 加依赖
Velocity引擎模板
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
test包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.5.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
lombok包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<optional>true</optional>
</dependency>
糊涂工具包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.7.20</version>
</dependency>
Swagger依赖包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
2 工具类
TODO是大家要改的,如果有特殊需求,可以自定义修改
package com.unicom.sh.content;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
@Slf4j
@SpringBootTest
public class MpGenerator {
String[] tableArray = {"cm_common_traffic_info"};
String[] tablePrefixArray = {"cm_"};
String packageName = "com.unicom.sh";
String moduleName = "content";
String url = "jdbc:mysql://127.0.0.1:3306/content?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai";
String userName = "root";
String password = "123456";
@Test
void test2() {
log.info("==========================准备生成文件...==========================");
for (String tableName : tableArray) {
test4(tableName);
}
log.info("==========================文件生成完成!!!==========================");
}
void test4(String tableName) {
StringBuffer projectPath = new StringBuffer();
String systemPath = System.getProperty("user.dir");
projectPath.append(systemPath.replaceAll("\\\\", "//")).append("//src//main");
DataSourceConfig dataSourceConfig = new DataSourceConfig.Builder(url, userName, password).build();
AutoGenerator generator = new AutoGenerator(dataSourceConfig);
GlobalConfig globalConfig = new GlobalConfig.Builder()
.fileOverride()
.disableOpenDir()
.outputDir(projectPath + "//java")
.author("admin")
.enableSwagger()
.build();
generator.global(globalConfig);
PackageConfig.Builder packageConfig = new PackageConfig.Builder()
.parent(packageName)
.moduleName(moduleName)
.entity("domain.entity")
.service("service")
.serviceImpl("service.impl")
.mapper("mapper")
.xml("mapper.xml")
.controller("controller");
Map<OutputFile, String> pathInfo = new HashMap<>();
pathInfo.put(OutputFile.mapperXml, projectPath + "//resources//mapper");
packageConfig.pathInfo(pathInfo);
generator.packageInfo(packageConfig.build());
TemplateConfig templateConfig = new TemplateConfig.Builder()
.disable(TemplateType.ENTITY)
.entity("/templates/entity.java")
.service("/templates/service.java")
.serviceImpl("/templates/serviceImpl.java")
.mapper("/templates/mapper.java")
.mapperXml("/templates/mapper.xml")
.controller("/templates/controller.java")
.build();
generator.template(templateConfig);
Map<String, Object> map = new HashMap<>();
setAttr(tableName, dataSourceConfig, map, tablePrefixArray);
generator.injection(injectionConfig().customMap(map).build());
StrategyConfig.Builder strategyConfig = new StrategyConfig.Builder()
.addInclude(tableName)
.addTablePrefix(tablePrefixArray);
strategyConfig
.entityBuilder().formatFileName("%sEntity")
.addSuperEntityColumns("id", "create_by", "create_time", "update_by", "update_time", "delete_flag")
.mapperBuilder().formatMapperFileName("%sMapper").formatXmlFileName("%sMapper")
.serviceBuilder().formatServiceFileName("I%sService")
.controllerBuilder().formatFileName("%sController");
generator.strategy(strategyConfig.build());
generator.execute();
}
private InjectionConfig.Builder injectionConfig() {
return new InjectionConfig.Builder().beforeOutputFile((tableInfo, objectMap) -> {
System.out.println("------------------tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size());
});
}
private void setAttr(String tableName, DataSourceConfig dataSourceConfig, Map<String, Object> map, String[] tablePrefixArray) {
List<Map<String, Object>> columns = new ArrayList<>();
String tableSql = "select table_name , table_comment from information_schema.tables " +
"where table_schema = (select database()) and table_name = '" + tableName + "'";
String columnSql = "select column_name , data_type , column_comment from information_schema.columns " +
"where table_name = '" + tableName + "' and table_schema = (select database()) and column_name != 'id_new'";
try (Connection conn = dataSourceConfig.getConn();
PreparedStatement psTable = conn.prepareStatement(tableSql);
ResultSet rsTable = psTable.executeQuery();
PreparedStatement ps = conn.prepareStatement(columnSql);
ResultSet rs = ps.executeQuery();
) {
if (rsTable.next()) {
String table_name = rsTable.getString("table_name");
map.put("tableName", table_name);
map.put("comment", rsTable.getString("table_comment"));
if (tablePrefixArray.length > 0) {
for (String s : tablePrefixArray) {
table_name = table_name.replaceAll(s, "");
}
}
map.put("upperClassName", StrUtil.upperFirst(StrUtil.toCamelCase(table_name)));
map.put("lowerClassName", StrUtil.toCamelCase(table_name));
}
while (rs.next()) {
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("column_name", rs.getString("column_name"));
columnMap.put("data_type", rs.getString("data_type"));
columnMap.put("javaLowerAttrName", StrUtil.toCamelCase(rs.getString("column_name")));
columnMap.put("javaAttrType", columnTypeToJavaType(rs.getString("data_type")));
columnMap.put("column_comment", rs.getString("column_comment"));
columns.add(columnMap);
}
} catch (Exception e) {
log.info("----------sql执行出错");
e.printStackTrace();
}
map.put("columns", columns);
map.put("datetime", DateUtil.now());
map.put("packageName", packageName);
map.put("moduleName", moduleName);
}
private String columnTypeToJavaType(String columnType) {
if (StrUtil.isNotEmpty(columnType)) {
if (Arrays.asList(COLUMN_TYPE_STR).contains(columnType)) {
return TYPE_STRING;
}
if (Arrays.asList(COLUMN_TYPE_TEXT).contains(columnType)) {
return TYPE_STRING;
}
if (Arrays.asList(COLUMN_TYPE_TIME).contains(columnType)) {
return TYPE_DATE;
}
if (Arrays.asList(COLUMN_TYPE_NUMBER).contains(columnType)) {
return TYPE_INTEGER;
}
if (Arrays.asList(COLUMN_TYPE_BIGINT).contains(columnType)) {
return TYPE_LONG;
}
if (Arrays.asList(COLUMN_TYPE_FLOAT).contains(columnType)) {
return TYPE_DOUBLE;
}
if (Arrays.asList(COLUMN_TYPE_DOUBLE).contains(columnType)) {
return TYPE_DOUBLE;
}
if (Arrays.asList(COLUMN_TYPE_DECIMAL).contains(columnType)) {
return TYPE_BIGDECIMAL;
}
}
return null;
}
public static final String[] COLUMN_TYPE_STR = {"char", "varchar", "nvarchar", "varchar2"};
public static final String[] COLUMN_TYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext"};
public static final String[] COLUMN_TYPE_TIME = {"datetime", "time", "date", "timestamp"};
public static final String[] COLUMN_TYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer", "bit"};
public static final String[] COLUMN_TYPE_BIGINT = {"bigint"};
public static final String[] COLUMN_TYPE_FLOAT = {"float"};
public static final String[] COLUMN_TYPE_DOUBLE = {"double"};
public static final String[] COLUMN_TYPE_DECIMAL = {"decimal"};
public static final String TYPE_STRING = "String";
public static final String TYPE_INTEGER = "Integer";
public static final String TYPE_LONG = "Long";
public static final String TYPE_DOUBLE = "Double";
public static final String TYPE_BIGDECIMAL = "BigDecimal";
public static final String TYPE_DATE = "Date";
}
3 模板
entity.java.vm
package ${packageName}.${moduleName}.domain.entity;
#set($list=["id","createBy","createTime", "updateBy", "updateTime", "deleteFlag"])
import com.baidu.sh.content.config.BaseEntity;
import lombok.Data;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableName;
@Data
@TableName("${tableName}")
@ApiModel(value = "${comment}", description = "${comment}对象 ${lowerClassName}")
public class ${upperClassName}Entity extends BaseEntity {
#foreach ($column in $columns)
## 排除父类字段
#if($list.contains($column.javaLowerAttrName))
#else
@ApiModelProperty(value = "$column.column_comment")
private $column.javaAttrType $column.javaLowerAttrName;
#end
#end
}
mapper.java.vm
package ${packageName}.${moduleName}.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import ${packageName}.${moduleName}.domain.entity.${upperClassName}Entity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ${upperClassName}Mapper extends BaseMapper<${upperClassName}Entity> {
}
mapper.xml.vm
<?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="${packageName}.${moduleName}.mapper.${upperClassName}Mapper">
<resultMap id="${lowerClassName}Map" type="${packageName}.${moduleName}.domain.entity.${upperClassName}Entity">
#foreach($column in $columns)
<result column="${column.column_name}" property="${column.javaLowerAttrName}"/>
#end
</resultMap>
</mapper>
service.java.vm
package ${packageName}.${moduleName}.service;
import com.baomidou.mybatisplus.extension.service.IService;
import ${packageName}.${moduleName}.domain.entity.${upperClassName}Entity;
public interface I${upperClassName}Service extends IService<${upperClassName}Entity> {
}
serviceImpl.java.vm
package ${packageName}.${moduleName}.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ${packageName}.${moduleName}.domain.entity.${upperClassName}Entity;
import ${packageName}.${moduleName}.mapper.${upperClassName}Mapper;
import ${packageName}.${moduleName}.service.I${upperClassName}Service;
import org.springframework.stereotype.Service;
@Service
public class ${upperClassName}ServiceImpl extends ServiceImpl<${upperClassName}Mapper, ${upperClassName}Entity> implements I${upperClassName}Service {
}
controller.java.vm
package ${packageName}.${moduleName}.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${packageName}.${moduleName}.domain.entity.${upperClassName}Entity;
import ${packageName}.${moduleName}.service.I${upperClassName}Service;
import ${packageName}.${moduleName}.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/${lowerClassName}")
@Api(value = "${lowerClassName}", tags = "${comment}管理模块")
public class ${upperClassName}Controller {
@Autowired
private I${upperClassName}Service ${lowerClassName}Service;
@ApiOperation(value = "分页查询", notes = "分页查询")
@GetMapping("/page")
public Result get${upperClassName}Page(Page page, ${upperClassName}Entity ${lowerClassName}Entity) {
return Result.ok(${lowerClassName}Service.page(page, Wrappers.query(${lowerClassName}Entity)));
}
@ApiOperation(value = "通过id查询", notes = "通过id查询")
@GetMapping("/{id}")
public Result getById(@PathVariable("id") Integer id) {
return Result.ok(${lowerClassName}Service.getById(id));
}
@ApiOperation(value = "新增${comment}", notes = "新增${comment}")
@PostMapping
public Result save(@RequestBody ${upperClassName}Entity ${lowerClassName}Entity) {
return Result.ok(${lowerClassName}Service.save(${lowerClassName}Entity));
}
@ApiOperation(value = "修改${comment}", notes = "修改${comment}")
@PutMapping
public Result updateById(@RequestBody ${upperClassName}Entity ${lowerClassName}Entity) {
return Result.ok(${lowerClassName}Service.updateById(${lowerClassName}Entity));
}
@ApiOperation(value = "通过id删除${comment}", notes = "通过id删除${comment}")
@DeleteMapping("/{id}")
public Result removeById(@PathVariable Integer id) {
return Result.ok(${lowerClassName}Service.removeById(id));
}
}
|