基本架构
相关依赖包
<properties>
<!--mybatis-plus版本-->
<mybatis-plus-boot-starter.version>3.2.0</mybatis-plus-boot-starter.version>
<!--mybatis-plus代码生成器引擎-->
<mybatis-plus-generator.version>3.3.1.tmp</mybatis-plus-generator.version>
</properties>
<dependencies> <!--springboot关于mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus-boot-starter.version}</version>
</dependency>
<!--代码生成器模板引擎 相关依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-generator.version}</version>
</dependency>
<!--MySQL支持-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>3.3.2.RELEASE</version>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
CodeGenerator(提示不需要动这个代码后面有配置)
package com.song.config;
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.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import utils.EmptyUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
/**
* @Description:代码生成器
*/
public class CodeGenerator {
public static void autoGenerator(){
//用来获取Mybatis-Plus.properties文件的配置信息
final ResourceBundle rb = ResourceBundle.getBundle("mybatis-plus-generrator");
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath =rb.getString("projectPath");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(rb.getString("author"));
gc.setOpen(false);
gc.setIdType(IdType.ID_WORKER);
// gc.setBaseColumnList(true);
//开启Xml属性名映射
gc.setBaseResultMap(true);
//将iservice前缀 i去掉
gc.setServiceName("%sService");
//关闭文件覆盖
gc.setFileOverride(false);
//指定时间处理类型
gc.setDateType(DateType.ONLY_DATE);
//实体属性 Swagger2 注解
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(rb.getString("url"));
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername(rb.getString("userName"));
dsc.setPassword(rb.getString("password"));
mpg.setDataSource(dsc);
//包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(rb.getString("moduleName"));
pc.setParent(rb.getString("parent"));
pc.setController("web");
//pc.setService("Service");
pc.setServiceImpl("service.impl");
pc.setEntity("pojo");
pc.setMapper("mapper");
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 projectPath + "/src/main/resources/mapper/" + pc.getModuleName()+"/sqlmap"
// + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
// }
// });
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
if ("true".equals(rb.getString("entity"))){
String entityFtlPath = rb.getString("entity.ftl.path");
if (!EmptyUtil.isNullOrEmpty(entityFtlPath)){
templateConfig.setEntity(entityFtlPath);
}
}else {
templateConfig.setEntity(null);
}
if ("true".equals(rb.getString("mapper"))){
String mapperFtlPath = rb.getString("mapper.ftl.path");
if (!EmptyUtil.isNullOrEmpty(mapperFtlPath)){
templateConfig.setMapper(mapperFtlPath);
}
}else {
templateConfig.setMapper(null);
}
if ("true".equals(rb.getString("service"))){
String serviceFtlPath = rb.getString("service.ftl.path");
if (!EmptyUtil.isNullOrEmpty(serviceFtlPath)){
templateConfig.setService(serviceFtlPath);
}
}else {
templateConfig.setService(null);
}
if ("true".equals(rb.getString("serviceImp"))){
String serviceImpFtlPath = rb.getString("serviceImp.ftl.path");
if (!EmptyUtil.isNullOrEmpty(serviceImpFtlPath)){
templateConfig.setServiceImpl(serviceImpFtlPath);
}
}else {
templateConfig.setServiceImpl(null);
}
if ("true".equals(rb.getString("controller"))){
String controllerFtlPath = rb.getString("controller.ftl.path");
if (!EmptyUtil.isNullOrEmpty(controllerFtlPath)){
templateConfig.setController(controllerFtlPath);
}
}else {
templateConfig.setController(null);
}
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// // 策略配置
// StrategyConfig strategy = new StrategyConfig();
// strategy.setNaming(NamingStrategy.underline_to_camel);
// strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.heima.springboot.basic.BasicPojo");
// strategy.setEntityLombokModel(true);
// strategy.setRestControllerStyle(true);
// // 写于父类中的公共字段
// String[] SuperEntityColumns =new String[]{"id","created_time","updated_time"};
// strategy.setSuperEntityColumns(SuperEntityColumns);
// strategy.setInclude(rb.getString("tableName").split(","));
// strategy.setControllerMappingHyphenStyle(true);
// String tablePrefix = rb.getString("tablePrefix");
// if (tablePrefix!=null){
// strategy.setTablePrefix(tablePrefix);
// }
// mpg.setStrategy(strategy);
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// mpg.execute();
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setInclude(rb.getString("tableName").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setEntityTableFieldAnnotationEnable(true);
String tablePrefix = rb.getString("tablePrefix");
if (tablePrefix!=null){
strategy.setTablePrefix(tablePrefix);
}
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
EmptyUtil
package utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* @Description 判断对象是否为空的工具类
*/
public abstract class EmptyUtil {
/**
*
* @方法名:对于String类型的非空判断
* @功能说明:对于String类型的非空判断
*/
public static boolean isNullOrEmpty(String str) {
if (str == null || "".equals(str.trim()) || "null".equalsIgnoreCase(str.trim()) || "undefined".equalsIgnoreCase(str.trim())) {
return true;
} else {
return false;
}
}
/**
*
* @方法名:对于StringBuffer类型的非空判断
* @功能说明:对于StringBuffer类型的非空判断
* @return boolean true-为空,false-不为空
*/
public static boolean isNullOrEmpty(StringBuffer str) {
return (str == null || str.length() == 0);
}
/**
*
* @方法名:对于string数组类型的非空判断
* @功能说明:对于string数组类型的非空判断
* @return boolean true-为空,false-不为空
*/
public static boolean isNullOrEmpty(String[] str) {
if (str == null || str.length == 0) {
return true;
} else {
return false;
}
}
/**
*
* @方法名:对于Object类型的非空判断
* @功能说明:对于Object类型的非空判断
* @return boolean true-为空,false-不为空
*/
public static boolean isNullOrEmpty(Object obj) {
if (obj == null || "".equals(obj)) {
return true;
} else {
return false;
}
}
/**
*
* @方法名:对于Object数组类型的非空判断
* @功能说明:对于Object数组类型的非空判断
* @return boolean true-为空,false-不为空
*/
public static boolean isNullOrEmpty(Object[] obj) {
if (obj == null || obj.length == 0) {
return true;
} else {
return false;
}
}
/**
*
* @方法名:对于Collection类型的非空判断
* @功能说明:对于Collection类型的非空判断
* @return boolean true-为空,false-不为空
*/
@SuppressWarnings("rawtypes")
public static boolean isNullOrEmpty(Collection collection) {
if (collection == null || collection.isEmpty()) {
return true;
} else {
return false;
}
}
/**
* @方法名:对于Map类型的非空判断
* @功能说明:对于Map类型的非空判断
* @return boolean true-为空,false-不为空
* @throws
*/
@SuppressWarnings("rawtypes")
public static boolean isNullOrEmpty( Map map) {
if (map == null || map.isEmpty()) {
return true;
} else {
return false;
}
}
/**
*
* @方法名:removeNullUnit
* @功能说明: 删除集合中的空元素
* @return
*/
public static <T> List<T> removeNullUnit(List<T> xllxList) {
List<T> need = new ArrayList<T>();
for (int i = 0; i < xllxList.size(); i++) {
if (!isNullOrEmpty(xllxList.get(i))) {
need.add(xllxList.get(i));
}
}
return need;
}
}
mybatis-plus-generrator.properties
这一块里面主要修改你的数据库地址和包名以及对应的表名
#数据库地址
url=jdbc:mysql://127.0.0.1:3306/***?useUnicode=true&useSSL=false&characterEncoding=utf8
#数据库用户
userName=root
#密码
password=
#当前路径就是你的需要导出生成的路径
projectPath=绝对路径
#不需要修改
author=Admin
#父包
parent=com.alibaba
#包名
moduleName=admin
#表名前缀,看需求是否需要删除,默认不删除
tablePrefix =
#Navicat对应db下的所有表名 需要修改
tableName=ad_vistor_statistics,ad_user_role,ad_user_opertion,ad_user_login,ad_user_equipment,ad_user,ad_strategy_group,ad_sensitive,ad_role_auth,ad_role,ad_recommend_strategy,ad_menu,ad_label,ad_function,ad_channel_label,ad_channel,ad_article_statistics
#不需要修改
entity=true
entity.ftl.path=/templates/entity.java
mapper=true
mapper.ftl.path=/templates/mapper.java
service=true
service.ftl.path=/templates/service.java
serviceImp=true
serviceImp.ftl.path=/templates/serviceImpl.java
controller=true
controller.ftl.path=/templates/controller.java
test
package com.itheima.boot;
import com.song.config.CodeGenerator;
/**
* @param
* @Description
* @Version v1.0
*/
public class test {
public static void main(String[] args) {
CodeGenerator.autoGenerator();
}
}
所有freemark模板
Controller层
package ${package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* @Description:${table.comment!} 前端控制器
*/
<#if restControllerStyle>
@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>
}
</#if>
entity层
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
<#--import lombok.Builder;-->
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.experimental.FieldNameConstants;
</#if>
/**
* @Description:${table.comment!}
*/
<#if entityLombokModel>
@Data
@NoArgsConstructor
@FieldNameConstants
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>
<#if entitySerialVersionUID>
private static final long serialVersionUID = 1L;
</#if>
<#-- @Builder-->
<#-- public ${entity}(Long id,<#list table.fields as field>${field.propertyType} ${field.propertyName}<#if field_has_next>,</#if></#list>){-->
<#-- super(id);-->
<#-- <#list table.fields as field>-->
<#-- this.${field.propertyName}=${field.propertyName};-->
<#-- </#list>-->
<#-- }-->
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
<#if swagger2>
@ApiModelProperty(value = "${field.comment}")
<#else>
/**
* ${field.comment}
*/
</#if>
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.name}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.name}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循环遍历 ---------->
<#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>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
protected Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#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>
}
mapper层
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
/**
* @Description:${table.comment!}Mapper接口
*/
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
</#if>
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>
</mapper>
service 层
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* @Description:${table.comment!} 服务类
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
</#if>
serviceImpl
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
/**
* @Description:${table.comment!} 服务实现类
*/
@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} {
}
</#if>
最后效果以entity为例
package com.heima.model.user.pojos;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.experimental.FieldNameConstants;
/**
* @Description:APP用户信息表
*/
@Data
@NoArgsConstructor
@FieldNameConstants
@EqualsAndHashCode(callSuper = false)
@TableName("ap_user")
@ApiModel(value="ApUser对象", description="APP用户信息表")
public class ApUser implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "密码、通信等加密盐")
@TableField("salt")
private String salt;
@ApiModelProperty(value = "用户名")
@TableField("name")
private String name;
@ApiModelProperty(value = "密码,md5加密")
@TableField("password")
private String password;
@ApiModelProperty(value = "手机号")
@TableField("phone")
private String phone;
@ApiModelProperty(value = "头像")
@TableField("image")
private String image;
@ApiModelProperty(value = "0 男 1 女 2 未知")
@TableField("sex")
private Boolean sex;
@ApiModelProperty(value = "0 未 1 是")
@TableField("is_certification")
private Boolean isCertification;
@ApiModelProperty(value = "是否身份认证 0否 1是")
@TableField("is_identity_authentication")
private Boolean isIdentityAuthentication;
@ApiModelProperty(value = "0正常 1锁定")
@TableField("status")
private Boolean status;
@ApiModelProperty(value = "0 普通用户 1 自媒体人 2 大V")
@TableField("flag")
private Boolean flag;
@ApiModelProperty(value = "注册时间")
@TableField("created_time")
private Date createdTime;
}