Mybatis-plus 自定义模板生成代码DTO、VO等

Mybatis-plus 自定义模板生成代码DTO、VO等

这里主要是介绍 Mybatis-plus 通过自定义模板自动生成增删改查等代码等,方便以后查阅!!!

一、简介

这里主要是介绍使用MyBatis-Plus生成基础代码,通过自定义 velocity 模板(controller、service、serviceImpl、dao)层,以及新增的DTO、queryDOT、VO类等,实现增删改查的基础代码生成。

二、操作步骤

(一)Maven依赖

 <dependency>
            <groupId>com.wl</groupId>
            <artifactId>cloud-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
        </dependency>

        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <!-- 代码自动生成器依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>

    <build>
        <!--扫描到java和resources下的xml等资源文件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.tld</include>
                </includes>
                <!--这里写成true会造成编译注释错误-->
                <filtering>false</filtering>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
                <!--这里写成true会造成编译注释错误-->
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

(二)生成代码

package com.wl.cloud.mbg;

import com.baomidou.mybatisplus.annotation.FieldFill;
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 java.util.*;

/**
 * @author: wanglin
 * @date: 2023-09-12 周二
 * @Version: 1.0
 * @Description:
 */
@SuppressWarnings("all")
public class MybatisGeneratorSystem {

    /**
     * 指定具体项目模块
     */
    public static String MOUDLE_NAME = "cloud-system";
    public static String AUTHOR_NAME = "wanglin";
    /**
     * 数据源信息
     */
    public static String URL = "jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
    public static String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
    public static String USERNAME = "root";
    public static String PASSWORD = "123456";
    /**
     * 包设置
     */
    public static String PARENT_PACKAGE = "com.wl.cloud.system";
    public static String MAPPER_PATH = "/src/main/resources/mapper/";
    /**
     * DTO/VO/QueryDTO 包路径
     */
    public static String PARENT_DTO_PATH = "\\src\\main\\java\\com\\wl\\cloud\\system\\support\\dto\\";
    public static String PARENT_VO_PATH = "\\src\\main\\java\\com\\wl\\cloud\\system\\support\\vo\\";
    public static String PARENT_Query_DTO_PATH = "\\src\\main\\java\\com\\wl\\cloud\\system\\support\\dto\\query\\";
    /**
     * DTO/VO/QueryDTO 包名
     */
    public static String PARENT_DTO_PACKAGE = "com.wl.cloud.system.support.dto";
    public static String PARENT_VO_PACKAGE = "com.wl.cloud.system.support.vo";
    public static String PARENT_Query_DTO_PACKAGE = "com.wl.cloud.system.support.dto.query";
    /**
     * DTO/VO/QueryDTO 自定义模板路径
     */
    public static String TEMPLATE_CONTROLLER_PATH = "/vm/java/controller.java";
    public static String TEMPLATE_SERVICE_PATH = "/vm/java/service.java";
    public static String TEMPLATE_SERVICEIMPL_PATH = "/vm/java/serviceImpl.java";
    public static String TEMPLATE_MAPPER_PATH = "/vm/java/mapper.java";
    public static String TEMPLATE_MAPPER_XML_PATH = "/vm/xml/mapper.xml.vm";
    /**
     * DTO/VO/QueryDTO 自定义模板路径
     */
    public static String TEMPLATE_DTO_PATH = "/vm/java/dto.java.vm";
    public static String TEMPLATE_VO_PATH = "/vm/java/vo.java.vm";
    public static String TEMPLATE_QUERY_DTO_PATH = "/vm/java/queryDto.java.vm";

    /**
     * controller 层请求路径前缀
     */
    public static String REQUEST_PATH_PREFIX = "cloud/sample/api/v1/";

    /**
     * 表前缀,生成实体类时,会自动去除表前缀,如:table: tb_task, class: Task
     */
    public static String TABLE_PREFIX_ENTITY = "gl_";

    /**
     * 需要生成的表名前缀,若为空,则默认是需要生成的表名是 TABLE_SUFFIX
     */
    public static String TABLE_PREFIX = "gl_sys_";
    /**
     * 需要生成的表名后缀,多个用逗号隔开
     */
//    public static String TABLE_SUFFIX = "menu,role,user_role,role_menu";
    public static String TABLE_SUFFIX = "menu";

    /**
     * DTO 忽略的字段
     */
    public static String DTO_IGNORE_FIELD = "id,createTime,updateTime,deleted";

    public static void main(String[] args) {
        if ("".equals(TABLE_SUFFIX)) {
            System.out.println("----->>>需要生成的表名为空");
            return;
        }
        //表拼接
        String[] tables;
        if ("".equals(TABLE_PREFIX)) {
            tables = TABLE_SUFFIX.split(",");
        } else {
            List<String> tableList = Arrays.asList(TABLE_SUFFIX.split(","));
            tables = tableList.stream().map(MybatisGeneratorSystem::apply).toArray(String[]::new);

        }
        System.out.println("表:");
        Arrays.stream(tables).forEach(System.out::println);

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/" + MOUDLE_NAME + "/src/main/java");//设置代码生成路径

        gc.setFileOverride(true);//是否覆盖以前文件
        gc.setOpen(false);//是否打开生成目录
        gc.setAuthor(AUTHOR_NAME);//设置项目作者名称
        // gc.setIdType(IdType.AUTO);//设置主键策略
        gc.setIdType(IdType.ASSIGN_ID);//设置主键策略
        gc.setBaseResultMap(true);//生成基本ResultMap
        gc.setBaseColumnList(true);//生成基本ColumnList
        gc.setServiceName("%sService");//去掉服务默认前缀
        gc.setDateType(DateType.ONLY_DATE);//设置时间类型
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL);
        dsc.setDriverName(DRIVER_NAME);
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(PARENT_PACKAGE);
        pc.setMapper("dao");
        //不生成实体类
        pc.setEntity("domain");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        //自定义配置,配置自定义属性注入
        InjectionConfig cfg = new InjectionConfig() {
            //在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性
            @Override
            public void initMap() {
                //自定义生成模板参数
                Map<String, Object> map = new HashMap<>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                //模板中获取值:${cfg.requestPathPrefix}
                map.put("requestPathPrefix", REQUEST_PATH_PREFIX);
                map.put("dtoPackage", PARENT_DTO_PACKAGE);
                map.put("voPackage", PARENT_VO_PACKAGE);
                map.put("queryDtoPackage", PARENT_Query_DTO_PACKAGE);
                map.put("dtoIgnoreFields", DTO_IGNORE_FIELD);
                this.setMap(map);
            }
        };

        // 如果模板引擎是 freemarker
        // String templatePath = "/templates/mapper.xml.vm.ftl";
        // 如果模板引擎是 velocity:
        // String templatePath = "/templates/mapper.xml.vm" ;
        //自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(TEMPLATE_MAPPER_XML_PATH) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/" + MOUDLE_NAME + MAPPER_PATH + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        //自定义生成类DTO/VO/QueryDOT
        focList.add(new FileOutConfig(TEMPLATE_DTO_PATH) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "\\" + MOUDLE_NAME + PARENT_DTO_PATH + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(TEMPLATE_VO_PATH) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "\\" + MOUDLE_NAME + PARENT_VO_PATH + tableInfo.getEntityName() + "VO" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(TEMPLATE_QUERY_DTO_PATH) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "\\" + MOUDLE_NAME + PARENT_Query_DTO_PATH + tableInfo.getEntityName() + "QueryDTO" + StringPool.DOT_JAVA;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义模板
        TemplateConfig templateConfig = new TemplateConfig();
        //控制:不生java下成xml
        templateConfig.setXml(null);
        templateConfig.setEntity(null);

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        templateConfig.setController(TEMPLATE_CONTROLLER_PATH);
        templateConfig.setService(TEMPLATE_SERVICE_PATH);
        templateConfig.setServiceImpl(TEMPLATE_SERVICEIMPL_PATH);
        templateConfig.setMapper(TEMPLATE_MAPPER_PATH);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig sc = new StrategyConfig();
        sc.setNaming(NamingStrategy.underline_to_camel);
        sc.setColumnNaming(NamingStrategy.underline_to_camel);
        sc.setEntityLombokModel(true);//自动lombok
        sc.setRestControllerStyle(true);
        sc.setControllerMappingHyphenStyle(true);
        sc.setLogicDeleteFieldName("deleted");//设置逻辑删除

        //设置自动填充配置
        TableFill gmt_create = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmt_modified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmt_create);
        tableFills.add(gmt_modified);
        sc.setTableFillList(tableFills);

        //乐观锁
        sc.setVersionFieldName("version");
        sc.setRestControllerStyle(true);//驼峰命名

        sc.setTablePrefix(TABLE_PREFIX_ENTITY); //设置表名前缀
        sc.setInclude(tables);//表名,多个英文逗号分割
        mpg.setStrategy(sc);

        // 生成代码
        mpg.execute();
    }

    private static String apply(String t) {
        return TABLE_PREFIX + t;
    }
}

三、三层模板

注意:不要更改模板的格式,模板格式已调成生成代码的样式!!!

controller层

controller.java.vm

package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${cfg.dtoPackage}.${entity}DTO;
import ${cfg.queryDtoPackage}.${entity}QueryDTO;
import ${cfg.voPackage}.${entity}VO;
import com.wl.cloud.core.dto.DataStoreDTO;
import com.wl.cloud.core.dto.RestResultDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * $!{table.comment} 前端控制器
 *
 * @author ${author}
 * @since ${date}
 */
#set($pathPrefix = "${cfg.requestPathPrefix}${table.entityPath}")
@Tag(name = "$!{table.comment}", description = "${table.controllerName}")
@Validated
@CrossOrigin
@RestController
@RequestMapping("$pathPrefix")
public class ${table.controllerName} {

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

    /**
     * 分页查询
     *
     * @param pageable
     * @return
     */
    @Operation(summary = "分页")
    @RequestMapping(value = "/page", method = {RequestMethod.POST, RequestMethod.GET})
    public RestResultDTO<DataStoreDTO<${entity}VO>>page(@ParameterObject @PageableDefault(sort = "createTime", direction = Sort.Direction.DESC) Pageable pageable,
                                                        @ParameterObject ${entity}QueryDTO queryDto){
        return RestResultDTO.newSuccess(${table.entityPath}Service.page(pageable, queryDto));
    }

    /**
     * 列表查询
     *
     * @param sort
     * @return
     */
    @Operation(summary = "列表")
    @RequestMapping(value = "/list", method = {RequestMethod.POST, RequestMethod.GET})
    public RestResultDTO<List<${entity}VO>>list(@ParameterObject @SortDefault(sort = "createTime", direction = Sort.Direction.DESC) Sort sort,
                                              @ParameterObject ${entity}QueryDTO queryDto){
        return RestResultDTO.newSuccess(${table.entityPath}Service.list(sort, queryDto));
    }

    /**
     * 保存
     *
     * @param dto
     * @return
     */
    @Operation(summary = "保存")
    @PostMapping("/save")
    public RestResultDTO<Void> save(@Validated @RequestBody ${entity}DTO dto){
        ${table.entityPath}Service.save(dto);
        return RestResultDTO.newSuccess();
    }

    /**
     * 修改
     *
     * @param dto
     * @return
     */
    @Operation(summary = "修改")
    @PostMapping(value = "/update")
    public RestResultDTO<Void> update(@Validated @RequestBody ${entity}DTO dto){
        ${table.entityPath}Service.update(dto);
        return RestResultDTO.newSuccess();
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @Operation(summary = "查询详情")
    @GetMapping("/get")
    public RestResultDTO<${entity}VO> get(@Parameter(description = "记录ID") @RequestParam String id){
        return RestResultDTO.newSuccess(${table.entityPath}Service.get(id));
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = {RequestMethod.GET})
    public RestResultDTO<Void> delete(@RequestParam Set<String> ids){
        ${table.entityPath}Service.delete(ids);
        return RestResultDTO.newSuccess(null,"删除成功");
    }
}

service层

service.java.vm

package ${package.Service};

import com.wl.cloud.core.dto.DataStoreDTO;
import ${cfg.dtoPackage}.${entity}DTO;
import ${cfg.queryDtoPackage}.${entity}QueryDTO;
import ${cfg.voPackage}.${entity}VO;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.List;
import java.util.Set;

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

    /**
     * 分页
     *
     * @param pageable
     * @param queryDto
     * @return
     */
    DataStoreDTO<${entity}VO> page(Pageable pageable, ${entity}QueryDTO queryDto);

    /**
     * 列表
     *
     * @param sort
     * @param queryDto
     * @return
     */
    List<${entity}VO> list(Sort sort, ${entity}QueryDTO queryDto);

    /**
     * 保存
     *
     * @param dto
     */
    void save(${entity}DTO dto);

    /**
     * 更新
     *
     * @param dto
     */
    void update(${entity}DTO dto);

    /**
     * 查看
     *
     * @param id
     * @return
     */
    ${entity}VO get(String id);

    /**
     * 删除
     *
     * @param ids
     */
    void delete(Set<String> ids);
}

serviceImpl层

serviceImpl.java.vm

package ${package.ServiceImpl};

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import ${package.Mapper}.${entity}Mapper;
import ${package.Entity}.${entity};
import ${package.Service}.${entity}Service;
import ${cfg.dtoPackage}.${entity}DTO;
import ${cfg.queryDtoPackage}.${entity}QueryDTO;
import ${cfg.voPackage}.${entity}VO;
import com.wl.cloud.core.dto.DataStoreDTO;
import com.wl.cloud.core.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * $!{table.comment} 服务实现类
 *
 * @author ${author}
 * @since ${date}
 */
@Service
public class ${table.serviceImplName} implements ${table.serviceName}{

    @Autowired
    private ${table.mapperName} ${table.entityPath}Mapper;

    @Transactional(readOnly = true)
    @Override
    public DataStoreDTO<${entity}VO> page(Pageable pageable, ${entity}QueryDTO queryDto) {
        QueryWrapper<${entity}> queryWrapper = this.buildQuery(queryDto);
        Page<${entity}> page = PageUtils.transferPage(pageable);
        Page<${entity}> result = this.${table.entityPath}Mapper.selectPage(page, queryWrapper);
        return new DataStoreDTO(result.getTotal(), this.transferVo(result.getRecords()));
    }

    @Transactional(readOnly = true)
    @Override
    public List<${entity}VO> list(Sort sort, ${entity}QueryDTO queryDto) {
        QueryWrapper<${entity}> queryWrapper = this.buildQuery(queryDto);
        PageUtils.transferSort(queryWrapper, sort);
        return this.transferVo(this.${table.entityPath}Mapper.selectList(queryWrapper));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(${entity}DTO dto) {
        // TODO 唯一性字段校验
        dto.setId(null);
        ${table.entityPath}Mapper.insert(this.transferEntity(null, dto));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(${entity}DTO dto) {
        Assert.hasText(dto.getId(), "id不能为空");
        // TODO 唯一性字段校验
        ${entity} entity = ${table.entityPath}Mapper.selectById(dto.getId());
        Assert.notNull(entity, "找不到id为 " + dto.getId() + " 的记录");
        ${table.entityPath}Mapper.updateById(this.transferEntity(entity, dto));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Set<String> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            ${table.entityPath}Mapper.deleteBatchIds(ids);
        }
    }

    @Transactional(readOnly = true)
    @Override
    public ${entity}VO get(String id) {
        Assert.hasText(id, "id不能为空");
        ${entity} entity = ${table.entityPath}Mapper.selectById(id);
        Assert.notNull(entity, "找不到id为 " + id + " 的记录");
        return this.transferVo(entity);
    }

    private QueryWrapper<${entity}> buildQuery(${entity}QueryDTO queryDto) {
        QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(queryDto)) {
            queryWrapper.lambda().eq(StringUtils.isNotBlank(queryDto.getId()), ${entity}::getId, queryDto.getId());
        }
        return queryWrapper;
    }

    private ${entity} transferEntity(${entity} entity, ${entity}DTO dto) {
        if (Objects.isNull(entity)) {
            entity = new ${entity}();
        }
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    private List<${entity}VO> transferVo(List<${entity}> entities) {
        if (CollectionUtils.isEmpty(entities)) {
            return Lists.newArrayList();
        }

        List<${entity}VO> voList = entities.stream().map(entity -> {
        ${entity}VO vo = new ${entity}VO();
        BeanUtils.copyProperties(entity, vo);
            return vo;
        }).collect(Collectors.toList());
        return voList;
    }

    private ${entity}VO transferVo(${entity} entity) {
        if (Objects.isNull(entity)) {
            return null;
        }
        ${entity}VO vo = new ${entity}VO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }
}

dao层

mapper.java.vm

package ${package.Mapper};

import ${package.Entity}.${entity};
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import ${cfg.voPackage}.${entity}VO;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * $!{table.comment} Mapper接口
 *
 * @author ${author}
 * @since ${date}
 */
@Mapper
public interface ${entity}Mapper extends BaseMapper<${entity}> {
    /**
    * 查询$!{table.comment}
    *
    * @return
    */
    List<${entity}VO> select${entity}List();
}

mapper.xml文件

mapper.xml.vm

<?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.columnName},
        #end
        ${table.fieldNames}
    </sql>
#end

    <select id="select${entity}List" resultType="${cfg.voPackage}.${entity}VO">
        select
        <include refid="${package.Mapper}.${table.mapperName}.Base_Column_List"></include>
        from ${table.name}
        order by create_time desc limit 10;
    </select>
</mapper>

四、新增类模板

DTO类

dto.java.vm

package ${cfg.dtoPackage};

import com.wl.cloud.core.dto.AbstractBaseDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import java.util.Date;

/**
 * $!{table.comment}
 *
 * @author ${author}
 * @since ${date}
 */
@Data
@Schema(description = "$!{table.comment}")
#set($ignoreFields = ${cfg.dtoIgnoreFields})
public class ${entity}DTO extends AbstractBaseDTO {
#if("$ignoreFields" == "")
    #foreach($field in ${table.fields})
        #if(${field.keyFlag})
            #set($keyPropertyName=${field.propertyName})
        #end
    #if("$!field.comment" != "")
    /**
     * ${field.comment}
     */
    #end
    @Schema(description = "$!{field.comment}")
    private ${field.propertyType} ${field.propertyName};
    #end
#else
    #foreach($field in ${table.fields})
        #set($flag = "0")
        #foreach($ignoreName in ${cfg.dtoIgnoreFields.split(",")})
            #if("$ignoreName" == "${field.propertyName}")
                #set($flag = "1")
                #break
            #end
        #end
        #if($flag == "0")
            #if(${field.keyFlag})
                #set($keyPropertyName=${field.propertyName})
            #end
    #if("$!field.comment" != "")
    /**
     * ${field.comment}
     */
    #end
    @Schema(description = "$!{field.comment} ${field.propertyName}")
    private ${field.propertyType} ${field.propertyName};
        #end
    #end
#end
}

queryDTO类

queryDto.java.vm

package ${cfg.queryDtoPackage};

import com.wl.cloud.core.dto.AbstractBaseDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import java.util.Date;

/**
 * $!{table.comment} 查询条件
 *
 * @author ${author}
 * @since ${date}
 */
@Data
@Schema(description = "$!{table.comment}")
public class ${entity}QueryDTO extends AbstractBaseDTO {
#foreach($field in ${table.fields})
    #if("$field.propertyName" == "id")
        #if(${field.keyFlag})
            #set($keyPropertyName=${field.propertyName})
        #end
        #if("$!field.comment" != "")
    /**
     * ${field.comment}
     */
    #end
    @Schema(description = "$!{field.comment}")
    private ${field.propertyType} ${field.propertyName};
    #end
#end
}

VO类

vo.java.vm

package ${cfg.voPackage};

import com.wl.cloud.core.dto.AbstractBaseDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import java.util.Date;

/**
 * $!{table.comment}
 *
 * @author ${author}
 * @since ${date}
 */
@Data
@Schema(description = "$!{table.comment}")
public class ${entity}VO extends AbstractBaseDTO {
#foreach($field in ${table.fields})
    #if(${field.keyFlag})
        #set($keyPropertyName=${field.propertyName})
    #end
    #if("$!field.comment" != "")
    /**
     * ${field.comment}
     */
    #end
    @Schema(description = "$!{field.comment}")
    private ${field.propertyType} ${field.propertyName};
#end
}

五、截图展示

在这里插入图片描述

关注林哥,持续更新哦!!!★,°:.☆( ̄▽ ̄)/$:.°★ 。

  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值