mybatis-plus 自定义模板-代码生成器

1:mybatis-plus 内置的模板缺点

只有基础的通用的方法(下图中的类中没有方法),没有自定义的延申方法,且生成的pojo没有注解(下图中的pojo中没有TableField注解)。

2:自定义模板效果

mybatis-plus 自定义模板-代码生成器_第1张图片

mybatis-plus 自定义模板-代码生成器_第2张图片

3:使用步骤


package com.draymond.mybatisplus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

/**
* @Auther: ZhangSuchao
* @Date: 2020/8/8 09:48
*/
public class Code {

  /**
   * 

* MySQL 生成演示 *

*/ public static void main(String[] args) { // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setActiveRecord(true); // 是否支持AR模式 gc.setAuthor("zsc"); // 作者 gc.setOutputDir("E:/IdeaProjects/draymond/springwork/mybatis-plus/src/main/java"); // 生成的路径 gc.setFileOverride(true); // 是否覆盖同名文件,默认是false gc.setIdType(IdType.AUTO); // 主键策略:自增 gc.setEnableCache(false); // XML 二级缓存 gc.setBaseResultMap(true); // XML ResultMap gc.setBaseColumnList(true); // 生成Sql片段 /* 自定义文件命名,注意 %s 会自动填充表实体属性! */ gc.setMapperName("%sDao"); gc.setXmlName("%sDao"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sController"); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); dsc.setUrl("jdbc:mysql://localhost:3306/test_data?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&autoReconnect=true"); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setCapitalMode(true); // 全局大写命名 strategy.setTablePrefix(new String[]{"tb_", "sys_"}); // 修改表前缀 strategy.setNaming(NamingStrategy.underline_to_camel); // 表名生成策略(下划线转驼峰) strategy.setInclude(new String[]{"tb_user"}); // 需要生成的表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.draymond.mybatisplus.code"); pc.setMapper("mapper"); pc.setEntity("model"); pc.setXml("xml"); pc.setController("controller"); pc.setService("service"); pc.setServiceImpl("service.impl"); // 自定义模板 TemplateConfig template = new TemplateConfig(); template.setController("mytemplates/mycontroller.vm"); template.setService("mytemplates/myservice.vm"); template.setServiceImpl("mytemplates/myserviceImpl.vm"); template.setMapper("mytemplates/mymapper.vm"); template.setXml("mytemplates/myxml.vm"); template.setEntity("mytemplates/myentity.vm"); template.setEntityKt("mytemplates/myentityDTO.vm"); // 设置整合 AutoGenerator mpg = new AutoGenerator(); mpg.setTemplateEngine(new VelocityTemplateEngine()); // 使用Veloctiy模板 mpg.setPackageInfo(pc); mpg.setStrategy(strategy); mpg.setDataSource(dsc); mpg.setGlobalConfig(gc); mpg.setTemplate(template); // 执行生成 mpg.execute(); } }

4:自定义的模板

4.1 controller

		package ${package.Controller};


import com.draymond.mybatisplus.code.model.${entity};
import com.draymond.mybatisplus.code.service.${table.serviceName} ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import com.baomidou.mybatisplus.core.metadata.IPage;


/**
* $!{table.comment} 前端控制器
* @author ${author}
* @since ${date}
*/


@RestController
@RequestMapping("/${table.entityPath}" )
public class ${table.controllerName} {

    @Autowired
    private ${table.serviceName}  ${table.entityPath}Service;

    /**
    * 保存
    *
    * @param model
    * @return
    */
    @RequestMapping("/save")
    public Object save(${entity} model) {
        ${table.entityPath}Service.save(model);
        return "success";
    }


    /**
    * 查询详情
    *
    * @param id
    * @return
    */
    @RequestMapping("/getById")
    public Object getById(Integer id) {
     ${entity} model = ${table.entityPath}Service.getById(id);
        // todo 再包装一层
        return model;
    }


    /**
    * 列表查询(非分页)
    *
    * @return
    */
    @RequestMapping("/list")
    public Object list() {
        ${entity} model = new  ${entity}();
        List<${entity}> list =  ${table.entityPath}Service.list(model);
        // todo 再包装一层
        return list;
    }


    /**
    * 列表查询(分页)
    *
    * @return
    */
    @RequestMapping("/pageList")
    public Object pageList(Integer pageNum, Integer pageSize) {

        ${entity} model = new  ${entity}();
        IPage page = ${table.entityPath}Service.pageList(model, pageNum, pageSize);
        // todo 再包装一层
        return page;
    }

}

4.2 entity模板

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 lombok.Data;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;

/**
* $!{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

@Data
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)
        #end
    #else
    @TableField("${field.annotationColumnName}")
    #end
    private ${field.propertyType} ${field.propertyName};
#end
## ----------  END 字段循环遍历  ----------


}

4.3 service

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import java.util.List;
import com.baomidou.mybatisplus.core.metadata.IPage;

/**
* 

* $!{table.comment} 服务类 *

* * @author ${author} * @since ${date} */ public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { /** * 查询 * * @param model * @return */ List<${entity}> list(${entity} model); /** * 分页查询 * * @param model * @param pageNum 第几页 * @param pageSize 每页数量 * @return */ IPage<${entity}> pageList(${entity} model, Integer pageNum, Integer pageSize); }

4.4 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;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 

* $!{table.comment} 服务实现类 *

* * @author ${author} * @since ${date} */ @Service public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { @Override public List< ${entity}> list(${entity} model) { QueryWrapper< ${entity}> wrapper = new QueryWrapper(); return super.list(wrapper); } @Override public IPage< ${entity}> pageList( ${entity} model, Integer pageNum, Integer pageSize) { QueryWrapper< ${entity}> wrapper = new QueryWrapper(model); return this.page(new Page<>(pageNum, pageSize), wrapper); } }

如果还需要其他的通用自定义方法,还可以继续添加

分页插件的注入

package com.draymond.mybatisplus.spring;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @Auther: ZhangSuchao
 * @Date: 2020/8/8 13:56
 */
@Component
@Configuration
public class ApplicationConfig {

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

}

ps:有问题清留言

你可能感兴趣的:(工具,mybatis)