自定义模板的MyBatisPlus

Gitee地址:https://gitee.com/xujiulong/my-batis-plus.git

1. 添加依赖

  • swagger2
  • lombok
  • MyBatisPlus里面集成了MyBatis 所以不用再加MyBatis依赖 否则容易报错
 
<dependency>
 <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger2artifactId>
    <version>2.9.2version>
dependency>
 
<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger-uiartifactId>
    <version>2.9.2version>
dependency>
 
<dependency> 
	<groupId>com.baomidougroupId> 
	<artifactId>mybatis-plus-boot-starterartifactId> 
	<version>3.2.0version> 
dependency>
<dependency>
   <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-generatorartifactId>
    <version>3.2.0version>
dependency>
 
<dependency>
    <groupId>org.freemarkergroupId>
    <artifactId>freemarkerartifactId>
    <version>2.3.30version>
dependency>
 
<dependency>
    <groupId>javax.validationgroupId>
    <artifactId>validation-apiartifactId>
    <version>2.0.1.Finalversion>
dependency>

2. application.properties

# 设置开发环境(使用性能分析插件要求为开发或测试环境)
spring.profiles.active=dev
# 端口号
spring.port-=9090

# 数据库连接配置
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# 配置日志 控制台输出sql语句
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

3. 代码自动生成器

新建一个Generator类 添加下面的main 修改对应 数据源 表名

public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String oPath = System.getProperty("user.dir");//得到当前项目的路径
        gc.setOutputDir(oPath + "/src/main/java");   //生成文件输出根目录
        gc.setAuthor("许久龙");  // 作者
        gc.setOpen(false);  // 生成代码后是否打开文件
        gc.setFileOverride(true);// 是否覆盖原文件
        //gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE); //注释的日期格式只显示时间
        gc.setMapperName("%sMapper");//去掉生成的Mapper文件前缀
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/company_frame?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置(可修改)
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.example.demo.system");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        //修改此生成路径
        String path="/src/main/java/com/example/demo/system";
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名及地址 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return oPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        focList.add(new FileOutConfig("/template/controller.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return oPath + path+ "/controller/" + tableInfo.getControllerName() + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig("/template/service.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return oPath + path+  "/service/" + tableInfo.getServiceName() + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig("/template/serviceImpl.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return oPath +  path+ "/service/impl/" + tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig("/template/entity.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return oPath +  path+ "/entity/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig("/template/mapper.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return oPath +  path+ "/mapper/" + tableInfo.getMapperName() + StringPool.DOT_JAVA;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig
                .setEntity(null)
                .setXml(null)
                .setMapper(null)
                .setService(null)
                .setServiceImpl(null)
                .setController(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);//开启实体类Lombok注解
        strategy.setRestControllerStyle(true);//生成Rest风格controller
        strategy.setEntityTableFieldAnnotationEnable(true); //生成@TableField
        strategy.setInclude(new String[]{
                "sys_dept", "sys_file", "sys_log", "sys_permission",
                "sys_role", "sys_role_permission", "sys_user_role",
                "sys_user", "sys_rotation_chart"
        });// 需要生成的表
        
		// 自动填充配置
		//TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
		//TableFill gmtModified = new TableFill("gmt_modified",FieldFill.INSERT_UPDATE);
		//ArrayList tableFills = new ArrayList<>();
		//tableFills.add(gmtCreate);
		//tableFills.add(gmtModified);
		//strategy.setTableFillList(tableFills);
		// 乐观锁
		//strategy.setVersionFieldName("version");
		
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("sys_"); //去掉表前缀
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
}

自定义模板的MyBatisPlus_第1张图片

4. 模板

在resources下新建template类放以下5个自定义模板

  • controller.java.ftl
package ${package.Controller};

import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import io.swagger.annotations.ApiOperation;
<#--import org.apache.shiro.authz.annotation.Logical;-->
<#--import org.apache.shiro.authz.annotation.RequiresPermissions;-->
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;
import javax.validation.Valid;
<#--import com.common.res.DataResult;-->
<#if restControllerStyle>
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* @author ${author}
* @since ${date}
*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("api")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
 <#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
 <#else>
public class ${table.controllerName} {
 </#if>

    @Autowired
    private ${table.serviceName} ${table.serviceName?uncap_first};

<#--    @ApiOperation(value = "${table.comment}分页列表", response = ${entity}.class)-->
<#--    @ApiImplicitParams({-->
<#--    @ApiImplicitParam(name = "page", value = "页面", dataType = "Long"),-->
<#--    @ApiImplicitParam(name = "size", value = "页面数据量", dataType = "Long"),-->
<#--    @ApiImplicitParam(name = "sort", value = "排序方式排序[true:正序; false:倒序]", dataType = "Boolean"),-->
<#--    @ApiImplicitParam(name = "sortName", value = "排序字段,参照返回字段", dataType = "String")})-->
<#--    @PostMapping(value = "/page")-->
<#--    public  Object list(@Valid @RequestBody ${entity} param) {-->

<#--    Object data = ${table.serviceName?uncap_first}.page(param);-->
<#--    return RetJson.ok(data);-->
<#--    }-->
    @GetMapping("/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}")
<#--    @RequiresPermissions("sys:${table.entityName?uncap_first}:list")-->
    @ApiOperation("${table.entityName}查询单个")
    public ResultVO get${table.entityName}(@RequestBody ${table.entityName} ${table.entityName?uncap_first}){
     ResultVO resultVO = ${table.entityName?uncap_first}Service.get${table.entityName}(${table.entityName} ${table.entityName?uncap_first});
     return  resultVO;
   }

    @GetMapping("/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}")
<#--    @RequiresPermissions("sys:${table.entityName?uncap_first}:list")-->
    @ApiOperation("${table.entityName}查询全部")
    public ResultVO getAll${table.entityName}(){
        ResultVO resultVO = ${table.entityName?uncap_first}Service.getAll${table.entityName}();
        return  resultVO;
    }

    @PostMapping("/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}")
<#--    @RequiresPermissions("sys:${table.entityName?uncap_first}:add")-->
    @ApiOperation("${table.entityName}新增")
    public ResultVO add(@Valid @RequestBody ${table.entityName} ${table.entityName?uncap_first}) {
        ResultVO resultVO = ${table.entityName?uncap_first}Service.add(${table.entityName} ${table.entityName?uncap_first});
        return  resultVO;
    }

    @PutMapping("/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}")
<#--    @RequiresPermissions("sys:${table.entityName?uncap_first}:update")-->
    @ApiOperation("${table.entityName}修改")
    public ResultVO update(@Valid @RequestBody ${table.entityName} ${table.entityName?uncap_first}) {
        ResultVO resultVO = ${table.entityName?uncap_first}Service.update(${table.entityName} ${table.entityName?uncap_first});
        returnresultVO;
    }


    @DeleteMapping(value = "/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}/{ids}")
<#--    @RequiresPermissions("sys:${table.entityName?uncap_first}:delete")-->
    @ApiOperation("${table.entityName}删除(单个条目)")
    public ResultVO remove(@NotBlank(message = "{required}") @PathVariable String ids) {
        ResultVO resultVO = ${table.entityName?uncap_first}Service.remove(String ids);
        return resultVO;
    }
}
</#if>
  • entity.java.ftl
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.Data;
import lombok.EqualsAndHashCode;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
</#if>

/**
 * @author ${author}
 * @since ${date}
 */
<#if entityLombokModel>
@Data
@EqualsAndHashCode
</#if>
@AllArgsConstructor
@NoArgsConstructor
<#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>
<#-- ----------  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.java.ftl
package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};

/**
 * ${table.comment!} Mapper 接口
 *
 * @author ${author}
 * @since ${date}
 */
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
</#if>
  • service.java.ftl
package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};

/**
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

<#--    /**-->
<#--    * ${table.entityName!}详情-->
<#--    * @param id-->
<#--    * @return-->
<#--    */-->
<#--    get${table.entityName}(String ${table.entityName?uncap_first}Id);-->

<#--    /**-->
<#--    * ${table.entityName!}详情-->
<#--    * @param id-->
<#--    * @return-->
<#--    */-->
<#--    getAll${table.entityName}();-->

<#--    /**-->
<#--    * ${table.entityName!}新增-->
<#--    * @param param 根据需要进行传值-->
<#--    * @return-->
<#--    */-->
<#--    void add(${entity} param);-->

<#--    /**-->
<#--    * ${table.entityName!}修改-->
<#--    * @param param 根据需要进行传值-->
<#--    * @return-->
<#--    */-->
<#--    void modify(${entity} param);-->

<#--    /**-->
<#--    * ${table.entityName!}删除(单个条目)-->
<#--    * @param id-->
<#--    * @return-->
<#--    */-->
<#--    void remove(String ${table.entityName}Id);-->
}

</#if>

  • serviceImpl.java.ftl
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} {

<#--  @Override-->
<#--  public DataResult<List getAll${table.entityName}(${table.entityName} ${table.entityName?uncap_first}){-->
<#--  DataResult result =DataResult.success();-->

<#--  return result;-->
<#--  }-->
<#--                         -->
<#--   @Override-->
<#--  public DataResult add(@Valid @RequestBody ${table.entityName} ${table.entityName?uncap_first}) {-->
<#--  DataResult result =DataResult.success();-->

<#--  return result;-->
<#--  }-->
<#--   @Override-->
<#--  public DataResult update(@Valid @RequestBody ${table.entityName} ${table.entityName?uncap_first}) {-->
<#--  DataResult result =DataResult.success();-->

<#--  return result;-->
<#--  }-->

<#--   @Override-->
<#--  public DataResult remove(@NotBlank(message = "{required}") @PathVariable String ids) {-->
<#--  DataResult result =DataResult.success();-->

<#--  return result;-->

}
</#if>

你可能感兴趣的:(java,mysql,spring)