mybatis-plus 工具自动给我们生成 Controller、Service、Entity、Mapper、Mapper.xml 层代码,在开发中对于简单的增删改查的业务能自动帮我们生成,大大减少我们的开发时间,话不多说直接上代码
简单的springboot项目这里就不演示了,搭建自行构建,pom.xml如下
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.6.3version>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>tel-mybatisartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>tel-mybatisname>
<description>tel-mybatisdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.26version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.20version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.0version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.4.0version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocityartifactId>
<version>1.7version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.75version>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.5.2version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>
package com.example.tel;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
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.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
/**
* @author DELL
*/
public class AutoGeneratorUtil {
/**
* 启动生成代码
*
* @param args
*/
public static void main(String[] args) {
System.out.println("------开始---------");
doGenerator();
System.out.println("------结束---------");
}
/**
* 基础配置
*/
private static final String OUTPUT_DIR = System.getProperty("user.dir") + "/tel-mybatis/src/main/java";
private static final String OUTPUT_DIR_MAPPER = System.getProperty("user.dir") + "/tel-mybatis";
private static final String AUTHOR = "yangzhen";
/**
* 数据库配置
*/
private static final DbType DB_TYPE = DbType.MYSQL;
private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
private static final String USER_NAME = "yourDBName";
private static final String PASSWORD = "yourDBPASSWORD";
private static final String URL = "yourDBUrl";
/**
* 需要生成的表,可一次生成多张表
*/
private static final String[] TABLES = {"sys_opera_log","sean"};
/**
* 生成包路径
*/
private static final String PACKAGE_PARENT = "com.example";
private static final String MODEL_NAME = "tel";
private static final String ENTITY = "entity";
private static final String MAPPER = "mapper";
private static final String MAPPER_XML = "mapper";
private static final String SERVICE = "service";
private static final String SERVICE_IMPL = "service.impl";
private static final String CONTROLLER = "controller";
public static void doGenerator() {
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
//代码生成存放位置
gc.setOutputDir(OUTPUT_DIR);
//是否重写
gc.setFileOverride(true);
gc.setActiveRecord(false);
//二级缓存
gc.setEnableCache(false);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
//设置swagger
gc.setSwagger2(false);
//是否打开本地目录
gc.setOpen(false);
gc.setAuthor(AUTHOR);
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceImplName("%sServiceImpl");
gc.setServiceName("%sService");
// gc.setServiceName("I%sService");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DB_TYPE);
dsc.setDriverName(DRIVER_NAME);
dsc.setUsername(USER_NAME);
dsc.setPassword(PASSWORD);
dsc.setUrl(URL);
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setInclude(TABLES);
strategy.setSuperEntityColumns(new String[]{});
//是否使用lombok
strategy.setEntityLombokModel(true);
//是否使用restController
strategy.setRestControllerStyle(true);
//strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
List<TableFill> tableFillList = CollUtil.newArrayList();
TableFill fill = new TableFill("update_time", FieldFill.INSERT_UPDATE);
tableFillList.add(fill);
fill = new TableFill("create_time", FieldFill.INSERT);
tableFillList.add(fill);
strategy.setTableFillList(tableFillList);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(MODEL_NAME);
pc.setParent(PACKAGE_PARENT);
// 代码生成包路径
pc.setEntity(ENTITY);
pc.setMapper(MAPPER);
// pc.setXml("/mapper");
pc.setService(SERVICE);
pc.setServiceImpl(SERVICE_IMPL);
pc.setController(CONTROLLER);
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return OUTPUT_DIR_MAPPER + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 注入自定义配置,可以在 VM 中使用 ${cfg.packageMy} 设置值
// InjectionConfig cfg = new InjectionConfig() {
// public void initMap() {
// Map map = new HashMap();
// map.put("packageMy", packageBase);
// this.setMap(map);
// }
// };
// mpg.setCfg(cfg);
TemplateConfig tc = new TemplateConfig();
tc.setEntity("templates/entity.java.vm");
tc.setMapper("templates/mapper.java.vm");
tc.setXml(null);
// tc.setXml("templates/mapper.xml.vm");
tc.setServiceImpl("templates/serviceImpl.java.vm");
tc.setService("templates/service.java.vm");
tc.setController("templates/controller.java.vm");
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
}
}
到这里已经可以生成简单的代码了,想特别定制,请接着往下。。。
这里提供简单的模板,模板放在resource/templates
下
package ${package.Controller};
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
import ${package.Service}.${entity}Service;
import ${package.Entity}.${entity};
import com.example.tel.model.ResultM;
import cn.hutool.core.util.StrUtil;
/**
*
* $!{table.comment} 前端控制器
*
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end
#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
@Autowired
private ${entity}Service ${table.entityPath}Service;
/**
* 新增
*/
@RequestMapping(method = RequestMethod.POST, value = "/add")
public ResultM add(@RequestBody ${entity} ${table.entityPath}, HttpServletRequest request,
HttpServletResponse response) {
${table.entityPath}Service.save(${table.entityPath});
return ResultM.ok();
}
/**
* 修改
*/
@RequestMapping(method = RequestMethod.POST, value = "/update")
public ResultM edit(@RequestBody ${entity} ${table.entityPath}, HttpServletRequest request,
HttpServletResponse response) {
${table.entityPath}Service.updateById(${table.entityPath});
return ResultM.ok();
}
/**
* 删除
*/
@RequestMapping(method = RequestMethod.POST, value = "/delete")
public ResultM delete(HttpServletRequest request, HttpServletResponse response,
String ids) {
List<String> idList = StrUtil.split(ids, ',');
${table.entityPath}Service.removeByIds(idList);
return ResultM.ok();
}
/**
* 查询详情
*/
@RequestMapping(method = RequestMethod.GET, value = "/detail")
public ResultM detail(HttpServletRequest request, HttpServletResponse response,
String id) {
${entity} ${table.entityPath} = ${table.entityPath}Service.getById(id);
return ResultM.ok(${table.entityPath});
}
/**
* 查询所有
*/
@RequestMapping(method = RequestMethod.GET, value = "/queryList")
public ResultM queryList(HttpServletRequest request, HttpServletResponse response) {
QueryWrapper<${entity}> wrapper = new QueryWrapper<>();
List<${entity}> list = ${table.entityPath}Service.list(wrapper);
return ResultM.ok(list);
}
/**
* 分页查询
*/
@RequestMapping(method = RequestMethod.GET, value = "/queryPageList")
public ResultM queryPageList(HttpServletRequest request, HttpServletResponse response,
${entity} query,
@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(name = "pageSize", defaultValue = "10") int pageSize) {
QueryWrapper<${entity}> wrapper = new QueryWrapper<>();
Page<${entity}> pg = new Page<${entity}>(pageNum, pageSize);
pg = ${table.entityPath}Service.page(pg, wrapper);
return ResultM.ok(pg);
}
}
#end
package ${package.Entity};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger2})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Data;
import lombok.EqualsAndHashCode;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end
import com.fasterxml.jackson.annotation.JsonFormat;
/**
*
* $!{table.comment}
*
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Data
#if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
#else
@EqualsAndHashCode(callSuper = false)
#end
#if(${chainModel})
@Accessors(chain = true)
#end
#end
#if(${table.convert})
@TableName("${table.name}")
#end
#if(${swagger2})
@ApiModel(value="${entity}对象", description="$!{table.comment}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#else
public class ${entity} implements Serializable {
#end
#if(${entitySerialVersionUID})
private static final long serialVersionUID = 1L;
#end
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
#if(${swagger2})
@ApiModelProperty(value = "${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.annotationColumnName}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.annotationColumnName}")
#end
## 乐观锁注解
#if(${versionFieldName}==${field.name})
@Version
#end
## 逻辑删除注解
#if(${logicDeleteFieldName}==${field.name})
@TableLogic
#end
## 时间格式转换
#if(${field.propertyType.equals("LocalDateTime")})
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
#end
private ${field.propertyType} ${field.propertyName};
#end
## ---------- END 字段循环遍历 ----------
#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
#if(${chainModel})
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
this.${field.propertyName} = ${field.propertyName};
#if(${chainModel})
return this;
#end
}
#end
## --foreach end---
#end
## --end of #if(!${entityLombokModel})--
#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";
#end
#end
#if(${activeRecord})
@Override
protected Serializable pkVal() {
#if(${keyPropertyName})
return this.${keyPropertyName};
#else
return null;
#end
}
#end
#if(!${entityLombokModel})
@Override
public String toString() {
return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{foreach.index}==0)
"${field.propertyName}=" + ${field.propertyName} +
#else
", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
"}";
}
#end
}
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.apache.ibatis.annotations.Mapper;
/**
*
* $!{table.comment} Mapper 接口
*
*
* @author ${author}
* @since ${date}
*/
@Mapper
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
#end
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"/>
#end
#if(${baseResultMap})
<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
#foreach($field in ${table.fields})
#if(${field.keyFlag})##生成主键排在第一位
<id column="${field.name}" property="${field.propertyName}" />
#end
#end
#foreach($field in ${table.commonFields})##生成公共字段
<result column="${field.name}" property="${field.propertyName}" />
#end
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
<result column="${field.name}" property="${field.propertyName}" />
#end
#end
resultMap>
#end
#if(${baseColumnList})
<sql id="Base_Column_List">
#foreach($field in ${table.commonFields})
${field.columnName},
#end
${table.fieldNames}
sql>
#end
mapper>
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
*
* $!{table.comment} 服务类
*
*
* @author ${author}
* @since ${date}
*/
#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
#end
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
/**
*
* $!{table.comment} 服务实现类
*
*
* @author ${author}
* @since ${date}
*/
@Service
#if(${kotlin})
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
#else
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
}
#end
可直接执行AutoGeneratorUtil
中main
方法生成代码。
简单的代码生成到这里就结束了,请大家多多指教