spring-mybatis-plus代码生成器代码

1. 首先需要导入Maven依赖包,使用的是velocity引擎,如果使用其他引擎,注意引擎的依赖包

<!--mybatis-plus代码生成器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.3.2</version>
</dependency>
<!--velocity模板引擎-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.2</version>
</dependency>

目录结构
在这里插入图片描述
在这里插入图片描述

2. 写生成的代码配置

主入口类

import org.junit.Test;
import java.util.LinkedHashMap;
public class GeneratorTest {
    @Test
    public void generator() {
    
        MyGenerator mysqlGenerator = new MyGenerator();
        //添加要生成的表
        /**
         * @Param String 表名
         * @Param MeteInfo 自定义信息
         * */
        LinkedHashMap<String, MeteInfo> tableMap = new LinkedHashMap<>();
        tableMap.put("sys_log", new MeteInfo("sysLog", "sysLog", "s_log"));
        mysqlGenerator.generator(tableMap);
    }
}

自定义表信息

import lombok.AllArgsConstructor;
import lombok.Data;
/**
 * 自定义表信息
 * */
@Data
@AllArgsConstructor
public class MeteInfo {
    /**
     * 变量名称
     * */
    private String variateName;
    /**
     * 对应controller类上的的请求路径
     * */
    private String url;
    /**
     * 别名
     * */
    private String tableAlias;
}

代码生成

import com.baomidou.mybatisplus.generator.AutoGenerator;
import java.util.Map;
public class MyGenerator extends SuperGenerator {
    /**
      * MySQL generator
     */
    public void generator(Map<String, MeteInfo> tableMap) {
        tableMap.forEach((tableName, meteInfo) -> {
            // 代码生成器
            AutoGenerator mpg = getAutoGenerator(tableName, meteInfo);
            mpg.execute();
        });
    }
}

配置数据源、全局配置、包配置、策略配置,相关描述参考MyBatis-Plus

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.PostgreSqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.io.File;
import java.util.*;

public class SuperGenerator {
  
    private static final String BASE_PATH = "/com/tyut";
    //
    private static final String BASE_PACKAGE = "com.tyut";
    // 父包名(即module公共路径)
    private static final String PARENT_PACKAGE = "com.tyut";
    // 包名
    private static final String PACKAGE = "";
    // 去除表名前缀的集合
    public static final String[] TABLE_PREFIX = { "t_" ,  "mu_" , "auth_" };


    /**
     * 获取TemplateConfig
     *
     * @return
     */
    protected TemplateConfig getTemplateConfig() {
        return new TemplateConfig().setXml(null);
    }

    /**
     * 获取InjectionConfig
     * 自定义配置设置
     *
     * @return
     */
    protected InjectionConfig getInjectionConfig(final MeteInfo meteInfo) {
        focList.add(new FileOutConfig("templates/mapper.xml.vm") {
            // 自定义输出文件目录
            @Override
            public String outputFile(TableInfo tableInfo) {
                return getResourcePath() + "/mapper/"  + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
		//可以继续添加其他自己的配置
		focList.add(new FileOutConfig("模板地址") {
            // 自定义输出文件目录
            @Override
            public String outputFile(TableInfo tableInfo) {
                return ”输出路径“;
            }
        });
        return new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("name" , meteInfo.getVariateName());
                map.put("url" , meteInfo.getUrl());
                map.put("tableAlias" , meteInfo.getTableAlias());
                map.put("basePackage" , BASE_PACKAGE);
                map.put("package" , PACKAGE);
                this.setMap(map);
            }
        }.setFileOutConfigList(focList);
    }

    /**
     * 获取PackageConfig
     *
     * @return
     */
    protected PackageConfig getPackageConfig() {
        return new PackageConfig()
                .setParent(PARENT_PACKAGE) //父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
                .setController("controller")
                .setEntity("model")
                .setMapper("mapper")
                .setService("service")
                .setServiceImpl("service.impl");
    }

    /**
     * 获取StrategyConfig
     *
     * @param tableName
     * @return
     */
    protected StrategyConfig getStrategyConfig(String tableName) {
//        List<TableFill> tableFillList = getTableFills();
        return new StrategyConfig().setCapitalMode(false)// 全局大写命名
                .setTablePrefix(TABLE_PREFIX)// 去除前缀
                .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略,设置命名规则下划线转驼峰
                // 自定义实体父类
//                .setSuperEntityClass("com.tyut.common.model.BaseModel")
                // 自定义实体,公共字段
//                .setSuperEntityColumns("id" , "update_time" , "create_time" , "create_user" , "update_user")
                // 自动填充的配置
//                .setTableFillList(tableFillList)
                // // 自定义 mapper 父类
                // .setSuperMapperClass("org.crown.framework.mapper.BaseMapper")
                // // 自定义 controller 父类
//                .setSuperControllerClass("com.tyut.commmon.controller.BaseController")
                // // 自定义 service 实现类父类
//                .setSuperServiceImplClass("com.tyut.common.service.impl.BaseServiceImpl")
                // // 自定义 service 接口父类
//                .setSuperServiceClass("com.tyut.common.service.BaseService")
                // 【实体】是否生成字段常量(默认 false)
                .setEntityColumnConstant(true)
                // 【实体】是否为构建者模型(默认 false)自3.3.2开始更名为 chainModel
//                .setEntityBuilderModel(true)
                .setChainModel(true)
                // 【实体】是否为lombok模型(默认 false)<a
                // href="https://projectlombok.org/">document</a>
                .setEntityLombokModel(true)
                // Boolean类型字段是否移除is前缀处理
                .setEntityBooleanColumnRemoveIsPrefix(true)
                // 生成 @RestController 控制器
                .setRestControllerStyle(true)
                // 设置表名,可以写多个表名
                .setInclude(tableName); //
    }

    /**
     * 获取TableFill策略,自动填充的配置
     *
     * @return
     */
    protected List<TableFill> getTableFills() {
        // 自定义需要填充的字段
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("createTime" , FieldFill.INSERT)); //设置时的生成策略
        tableFillList.add(new TableFill("updateTime" , FieldFill.INSERT_UPDATE)); //设置更新时间的生成策略
        tableFillList.add(new TableFill("createUser" , FieldFill.INSERT));
        tableFillList.add(new TableFill("updateUser" , FieldFill.INSERT_UPDATE));
        return tableFillList;
    }

    /**
     * 获取DataSourceConfig
     *
     * @return
     */
    protected DataSourceConfig getDataSourceConfig() {
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new PostgreSqlTypeConvert() {
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                // 或者使用1.8
                if (fieldType.startsWith("timestamp")) {
                    return DbColumnType.DATE;
                }
                if (fieldType.startsWith("date")) {
                    return DbColumnType.DATE;
                }
                if (fieldType.startsWith("time")) {
                    return DbColumnType.DATE;
                }
                if (fieldType.startsWith("datetime")) {

                    return DbColumnType.DATE;
                }
                return super.processTypeConvert(globalConfig, fieldType);
            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/agriculture");
        return dsc;
    }

    /**
     * 获取GlobalConfig
     *
     * @return
     */
    protected GlobalConfig getGlobalConfig() {
        return new GlobalConfig().setOutputDir(getJavaPath())// 输出目录
                .setFileOverride(true)// 是否覆盖文件
                .setActiveRecord(false)// 开启 activeRecord 模式
                .setEnableCache(false)// XML 二级缓存
                .setBaseResultMap(true)// XML ResultMap
                .setBaseColumnList(true)// XML columList
                .setKotlin(false) // 是否生成 kotlin 代码
                .setOpen(false).setAuthor("chen") // 作者
                // 自定义文件命名,注意 %s 会自动填充表实体属性!
                .setEntityName("%s")
                .setMapperName("%sMapper")
                .setXmlName("%sMapper")
                .setServiceName("%sService")
                .setServiceImplName("%sServiceImpl")
                .setControllerName("%sController");
    }

    /**
     * 获取根目录
     *
     * @return
     */
    private String getRootPath() {

        return "E://auto//";
        // 获取当前类的所在工程路径; 如果不加“/”  获取当前类的加载目录
//        String file = Objects.requireNonNull(SuperGenerator.class.getClassLoader().getResource("")).getFile();
//        return new File(file).getParentFile().getParent();
    }

    /**
     * 获取JAVA目录
     *
     * @return
     */
    public String getJavaPath() {
        System.out.println(getRootPath() + "\\src\\main\\java");
        return getRootPath() + "/src/main/java";
    }

    /**
     * 获取Resource目录
     *
     * @return
     */
    protected String getResourcePath() {
        return getRootPath() + "/src/main/resources";
    }

    /**
     * 获取AutoGenerator
     *
     * @param tableName
     * @return
     */
    protected AutoGenerator getAutoGenerator(String tableName, MeteInfo meteInfo) {
        return new AutoGenerator()
                // 全局配置
                .setGlobalConfig(getGlobalConfig())
                // 数据源配置
                .setDataSource(getDataSourceConfig())
                // 策略配置
                .setStrategy(getStrategyConfig(tableName))
                // 包配置
                .setPackageInfo(getPackageConfig())
                // 注入自定义配置,自定义返回配置 Map 对象
                // 该对象可以传递到模板引擎通过 cfg.xxx 引用
                .setCfg(getInjectionConfig(meteInfo)).setTemplate(getTemplateConfig());
    }

}

4. 写模板引擎

controller类
package ${package.Controller};

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${cfg.basePackage}.common.controller.BaseController;
import ${cfg.basePackage}.common.query.Operator;
import ${cfg.basePackage}.common.query.Restrictions;
import ${cfg.basePackage}.common.query.SimpleExpression;
import ${cfg.basePackage}.common.response.BaseResult;
import ${cfg.basePackage}.common.util.BeanUtils;
import ${cfg.basePackage}.web.dto.request.${cfg.package}.Post${entity};
import ${cfg.basePackage}.web.dto.request.${cfg.package}.Put${entity};
import ${cfg.basePackage}.dao.${cfg.package}.model.${entity};
import ${cfg.basePackage}.${cfg.package}.service.${table.serviceName};
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * describe:$!{table.comment} 前端控制器
 *
 * @author ${author}
 * @date ${date}
 */
@Api(value = "$!{table.comment}管理", tags = "$!{table.comment}")
@RestController
@RequestMapping(value = "/${cfg.url}")
public class ${table.controllerName} extends BaseController {

    @Autowired
    private ${table.serviceName} ${cfg.name}Service;
    #set($hasDisabledField = false)
    #foreach($field in ${table.fields})
    #if(${field.name} == "disabled")
    #set($hasDisabledField = true)
    #end
    #end

    @ApiOperation("添加-$!{table.comment}")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public BaseResult<String> create(@RequestBody @Valid Post${entity} input, BindingResult br) {

        verifyParams(br);
        ${entity} ${cfg.name} = new ${entity}();
        BeanUtils.copyProperties(input, ${cfg.name});
        ${cfg.name}Service.save${entity}(${cfg.name});

        return BaseResult.SUCCESS;
    }

    @ApiOperation("删除-$!{table.comment}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public BaseResult<String> delete(@PathVariable("id") Long id){
        ${cfg.name}Service.delete${entity}(id);
        return BaseResult.SUCCESS;
    }

    @ApiOperation("更新-$!{table.comment}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public BaseResult<String> update(@PathVariable("id") Long id, @RequestBody @Valid Put${entity} input, BindingResult br) {
        verifyParams(br);
        ${entity} ${cfg.name} = new ${entity}();
        BeanUtils.copyProperties(input, ${cfg.name});
        ${cfg.name}.setId(id);
        ${cfg.name}Service.update${entity}(${cfg.name});
        return BaseResult.SUCCESS;
    }

    @ApiOperation("获取单个-$!{table.comment}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public BaseResult<${entity}> get(@PathVariable("id") Long id) {
        return BaseResult.success(${cfg.name}Service.get${entity}ById(id));
    }

    @ApiOperation("分页查询-$!{table.comment}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = false, dataType = "long", paramType = "query")
    })
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public BaseResult<IPage<${entity}>> page(
            Page<${entity}> page,
            @RequestParam(value = "id", required = false) Long id
    ) {
        checkPage(page);
        List<SimpleExpression> queryList = new ArrayList<>();
        queryList.add(SimpleExpression.set(${entity}.ID, id, Operator.EQ));
        return BaseResult.success(${cfg.name}Service.page(page, Restrictions.getEw(queryList)));
    }

    @ApiOperation("列表查询-$!{table.comment}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = false, dataType = "long", paramType = "query")
    })
    @RequestMapping(value = "", method = RequestMethod.GET)
    public BaseResult<List<${entity}>> list(
            @RequestParam(value = "id", required = false) Long id
    ) {
        List<SimpleExpression> queryList = new ArrayList<>();
        queryList.add(SimpleExpression.set(${entity}.ID, id, Operator.EQ));
        #if(${hasDisabledField})
queryList.add(SimpleExpression.set(${entity}.DISABLED, ${entity}.DISABLED_ENABLE, Operator.EQ));
        #end
return BaseResult.success(${cfg.name}Service.list(Restrictions.getEw(queryList)));
    }
    #if(${hasDisabledField})

    @ApiOperation("启用-$!{table.comment}")
    @RequestMapping(value = "/{id}/enable", method = RequestMethod.PUT)
    public BaseResult<String> enable(@PathVariable("id") Long id){
        ${cfg.name}Service.enable(id);
        return BaseResult.SUCCESS;
    }

    @ApiOperation("禁用-$!{table.comment}")
    @RequestMapping(value = "/{id}/disable", method = RequestMethod.PUT)
    public BaseResult<String> disable(@PathVariable("id") Long id){
        ${cfg.name}Service.disable(id);
        return BaseResult.SUCCESS;
    }
    #end

}


实体类,如果要生成其他的Vo、Bo、Dto类等的时候,可以在实体类的基础上修改。

package ${cfg.basePackage}.dao.model;
    #set($hasLongField = false) #foreach($field in ${table.fields}) #if(${field.columnType} == "LONG") #set($hasLongField = true) #end #end

#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${entityLombokModel})
#if(${hasLongField})
import com.alibaba.fastjson.annotation.JSONField;
import com.meinergy.chargingpile.common.config.LongSerializeConfig;
#end
import lombok.Data;
import lombok.EqualsAndHashCode;
#end
import io.swagger.annotations.ApiModelProperty;
import java.util.Map;
import java.util.HashMap;

/**
 * describe:$!{table.comment}
 *
 * @author autogen
 * @date ${date}
 */
#if(${entityLombokModel})
@Data
#if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
#end
#end
#if(${table.convert})
@TableName("${table.name}")
#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

    private static final long serialVersionUID = 1L;

## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
    /** ${field.comment}.*/
    @ApiModelProperty(value = "${field.comment}")
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
    @TableId(value = "${field.name}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
    @TableId(value = "${field.name}", type = IdType.${idType})
#elseif(${field.convert})
    @TableId("${field.name}")
#end
## 普通字段
#elseif(${field.fill})
## -----   存在字段填充设置   -----
#if(${field.convert})
    @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
    @TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
    @TableField("${field.name}")
#end
## 乐观锁注解
#if(${versionFieldName}==${field.name})
    @Version
#end
## 逻辑删除注解
#if(${logicDeleteFieldName}==${field.name})
    @TableLogic
#end
## 避免精度丢失
#if(${field.columnType} == "LONG")
    @JSONField(serializeUsing = LongSerializeConfig.Long2StringSerializer.class)
#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(${entityBuilderModel})
    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(${entityBuilderModel})
        return this;
#end
    }
#end
#end

#if(${entityColumnConstant})
#foreach($field in ${table.fields})
    public static final String ${field.name.toUpperCase()} = "${field.name}";

#end
    public static final String TABLE_ALIAS = "${cfg.tableAlias}.";

	/* 状态列表 */
    ## 格式 {no:0,拒绝;yes:1,同意}
#foreach($field in ${table.fields})
#if(${field.comment} && ${field.comment.indexOf("{")} !=-1 && ${field.comment.indexOf("}")} !=-1 && ${field.comment.indexOf(";")} !=-1 && ${field.comment.indexOf(":")})
#set ($start = $field.comment.indexOf("{") + 1)
#set ($end = $field.comment.indexOf("}"))
#set ($commentStr = $field.comment.substring($start,$end).replaceAll("'",'"'))
#set ($commentFields = $commentStr.split(";"))
#if($commentFields.size()>1)
#foreach($commentField in $commentFields)
#set ($array1 = $commentField.split(":"))
#set ($array2 = $array1.get(1).split(","))
#set ($code = $array1.get(0).toUpperCase())
#set ($value = $array2.get(0))
#set ($message = $array2.get(1))
	/** ${field.name}:${message}.*/
	public static final ${field.propertyType} ${field.name.toUpperCase()}_${code} = $value;
#end
    /** ${field.comment} 状态Map */
    public static Map<${field.propertyType}, String> ${field.name.toUpperCase()}_MAP = new HashMap<>();
    /** ${field.comment} 状态Map 反向 */
    public static Map<String, ${field.propertyType}> ${field.name.toUpperCase()}_STR_MAP = new HashMap<>();
    static {
    #foreach($commentField in $commentFields)
        #set ($array1 = $commentField.split(":"))
        #set ($array2 = $array1.get(1).split(","))
        #set ($code = $array1.get(0).toUpperCase())
        #set ($value = $array2.get(0))
        #set ($message = $array2.get(1))
    ${field.name.toUpperCase()}_MAP.put($value, "${message}");
        ${field.name.toUpperCase()}_STR_MAP.put("${message}", $value);
    #end
}
#end
#end
#end

#end
#if(${activeRecord})
    @Override
    protected Serializable pkVal() {
#if(${keyPropertyName})
        return this.${keyPropertyName};
#else
        return this.id;
#end
    }

#end
#if(!${entityLombokModel})
    @Override
    public String toString() {
        return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{velocityCount}==1)
        "${field.propertyName}=" + ${field.propertyName} +
#else
        ", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
        "}";
    }
#end
}

service类

package ${package.Service};

import ${package.Entity}.${entity};
import ${cfg.basePackage}.common.service.BaseService;

/**
 * describe:$!{table.comment} 服务类
 *
 * @author ${author}
 * @date ${date}
 */
#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends BaseService<${entity}> {

    /**
    * 添加 $!{table.comment}
     *
    * @param ${cfg.name} $!{table.comment}
    */
    void save${entity}(${entity} ${cfg.name});

    /**
    * 删除 $!{table.comment}
     *
    * @param id 主键
    */
    void delete${entity}(Long id);

    /**
    * 更新 $!{table.comment}
     *
    * @param ${cfg.name} $!{table.comment}
    */
    void update${entity}(${entity} ${cfg.name});

    /**
    * 获取 $!{table.comment}(不存在时会抛异常)
     *
    * @param id 主键
    * @return $!{table.comment}
    */
    ${entity} get${entity}ById(Long id);

    #foreach($field in ${table.fields})
    #if(${field.name} == "disabled")

    /**
     * 启用 $!{table.comment}
     *
     * @param id 主键
     */
    void enable(Long id);

    /**
     * 禁用 $!{table.comment}
     *
     * @param id 主键
     */
    void disable(Long id);
    #end
    #end

}
#end

service实现类

package ${package.ServiceImpl};

import ${cfg.basePackage}.common.exception.GlobalException;
import ${cfg.basePackage}.common.response.BaseResultEnum;
import ${cfg.basePackage}.common.service.impl.BaseServiceImpl;
import ${package.Mapper}.${table.mapperName};
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
#foreach($field in ${table.fields})
    #if(${field.name} == "disabled")
    import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
    #end
#end

/**
 * describe:$!{table.comment} 服务实现类
 *
 * @author ${author}
 * @date ${date}
 */
@Service
#if(${kotlin})
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

        }
#else
        public class ${table.serviceImplName} extends BaseServiceImpl<${table.mapperName}, ${entity}>implements ${table.serviceName} {

        @Override
        public void save${entity}(${entity} ${cfg.name}){
        this.save(${cfg.name});
        }

        @Override
        public void delete${entity}(Long id){
    ${entity} ${cfg.name} =getById(id);
        if(${cfg.name} ==null){
        throw new GlobalException(BaseResultEnum.NOT_EXISTS);
        }
        removeById(id);
        }

        @Override
        public void update${entity}(${entity} ${cfg.name}){
    ${entity} db${entity} =getById(${cfg.name}.getId());
        if(db${entity} ==null){
        throw new GlobalException(BaseResultEnum.NOT_EXISTS);
        }
        updateById(${cfg.name});
        }

        @Override
        public ${entity} get${entity}ById(Long id){
    ${entity} ${cfg.name} =getById(id);
        if(${cfg.name} ==null){
        throw new GlobalException(BaseResultEnum.NOT_EXISTS);
        }
        return ${cfg.name};
        }
    #foreach($field in ${table.fields})
        #if(${field.name} == "disabled")

                @Override
                public void enable(Long id){
            ${entity} ${cfg.name} =getById(id);
                if(${cfg.name} ==null){
                throw new GlobalException(BaseResultEnum.NOT_EXISTS);
                }
            ${entity} update${entity} =new ${entity}();
                update${entity}.setDisabled(${entity}.DISABLED_ENABLE);

                this.update(update${entity},new UpdateWrapper<${entity}>()
                .eq(${entity}.ID,id).eq(${entity}.DISABLED, ${entity}.DISABLED_DISABLE));
                }

                @Override
                public void disable(Long id){
            ${entity} ${cfg.name} =getById(id);
                if(${cfg.name} ==null){
                throw new GlobalException(BaseResultEnum.NOT_EXISTS);
                }
            ${entity} update${entity} =new ${entity}();
                update${entity}.setDisabled(${entity}.DISABLED_DISABLE);

                this.update(update${entity},new UpdateWrapper<${entity}>()
                .eq(${entity}.ID,id).eq(${entity}.DISABLED, ${entity}.DISABLED_ENABLE));
                }
        #end
    #end

        }
#end

Mapper类

package ${package.Mapper};

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

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

        }
#end

mapper.xml文件

<?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"/>

#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.name},
#end
        ${table.fieldNames}

    </sql>

#end
</mapper>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值