自学内容网 自学内容网

mybatis-plus模板引擎代码生成

Gradle依赖:

dependencies {
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter
    implementation 'org.springframework.boot:spring-boot-starter'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
    implementation 'org.springframework.boot:spring-boot-starter-web'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jdbc
    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    // https://mvnrepository.com/artifact/com.mysql/mysql-connector-j
    implementation 'com.mysql:mysql-connector-j'
    // https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter
    implementation 'com.baomidou:mybatis-plus-boot-starter:3.5.7'
    // https://mvnrepository.com/artifact/org.mybatis/mybatis-spring
    implementation 'org.mybatis:mybatis-spring:3.0.3'
    // https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator
    implementation 'com.baomidou:mybatis-plus-generator:3.5.7'
    // https://mvnrepository.com/artifact/commons-io/commons-io
    implementation 'commons-io:commons-io:2.16.1'
    // https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
    implementation 'org.apache.commons:commons-lang3:3.14.0'
    // https://mvnrepository.com/artifact/org.apache.commons/commons-text
    implementation 'org.apache.commons:commons-text:1.12.0'
    // https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-ui
    implementation 'org.springdoc:springdoc-openapi-ui:1.8.0'
    // https://mvnrepository.com/artifact/org.apache.velocity/velocity-engine-core
    implementation 'org.apache.velocity:velocity-engine-core:2.3'
    implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
    implementation 'org.springdoc:springdoc-openapi-starter-webmvc-api:2.5.0'
}

项目结构:
在这里插入图片描述
config包

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("代码生成")
                        .contact(new Contact())
                        .description("代码生成API")
                        .version("v1.0.0")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("外部文档")
                        .url("https://springshop.wiki.github.org/docs"));
    }

}

controller包:

@Tag(name = "代码生成工具控制器")
@ResponseBody
@RestController
@RequestMapping("/code/generator")
@Schema(description = "代码生成工具控制器")
@AllArgsConstructor
public class CodeGeneratorController {

    private MySqlCodeGeneratorService mySqlCodeGeneratorService;

    @Operation(summary = "代码生成工具控制器", description = "代码生成工具控制器")
    @PostMapping("/mysql")
    public void mysql(HttpServletResponse response, @RequestBody BatchCodeGenerateMySqlDto dto) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream), StandardCharsets.UTF_8);
        mySqlCodeGeneratorService.codeGeneratorZip(zipOutputStream, dto);
        IOUtils.closeQuietly(zipOutputStream);
        byte[] bytes = outputStream.toByteArray();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + bytes.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(bytes, response.getOutputStream());
    }
}

dto包

@Getter
@Setter
@Schema(name = "批量代码生成对象(MySql)")
public class BatchCodeGenerateMySqlDto implements Serializable {
    @Serial
    private static final long serialVersionUID = 42L;

    @Schema(description = "数据库表所属数据源", example = "demo")
    private String tableSchema;

    @Schema(description = "表名表名称前缀", example = "system_")
    private String tableNamePrefix;

    @Schema(description = "表名称列表", example = "['user','role','dept']")
    private List<String> tableNameList;

    @Schema(description = "包地址", example = "org.module.aaa")
    private String packageAddress;

    @Schema(description = "作者", example = "张三")
    private String author;
}

entity包

@Getter
@Setter
@TableName(value = "information_schema.COLUMNS")
@Schema(description = "MySql列信息")
public class MySqlColumn implements Serializable {
    @Serial
    private static final long serialVersionUID = 42L;

    @Schema(description = "表目录")
    @TableField(value = "TABLE_CATALOG")
    private String tableCatalog;

    @Schema(description = "表架构")
    @TableField(value = "TABLE_SCHEMA")
    private String tableSchema;

    @Schema(description = "表名称")
    @TableField(value = "TABLE_NAME")
    private String tableName;

    @Schema(description = "列名")
    @TableField(value = "COLUMN_NAME")
    private String columnName;

    @Schema(description = "序号位置")
    @TableField(value = "ORDINAL_POSITION")
    private Integer ordinalPosition;

    @Schema(description = "列默认值")
    @TableField(value = "COLUMN_DEFAULT")
    private String columnDefault;

    @Schema(description = "可为空")
    @TableField(value = "IS_NULLABLE")
    private String isNullable;

    @Schema(description = "数据类型")
    @TableField(value = "DATA_TYPE")
    private String dataType;

    @Schema(description = "字符最大长度")
    @TableField(value = "CHARACTER_MAXIMUM_LENGTH")
    private Long characterMaximumLength;

    @Schema(description = "字符八进制长度")
    @TableField(value = "CHARACTER_OCTET_LENGTH")
    private Long characterOctetLength;

    @Schema(description = "数字精度")
    @TableField(value = "NUMERIC_PRECISION")
    private Long numericPrecision;

    @Schema(description = "数字比例")
    @TableField(value = "NUMERIC_SCALE")
    private Long numericScale;

    @Schema(description = "日期时间精度")
    @TableField(value = "DATETIME_PRECISION")
    private Integer datetimePrecision;

    @Schema(description = "字符集名称")
    @TableField(value = "CHARACTER_SET_NAME")
    private String characterSetName;

    @Schema(description = "排序规则名称")
    @TableField(value = "COLLATION_NAME")
    private String collationName;

    @Schema(description = "列类型")
    @TableField(value = "COLUMN_TYPE")
    private String columnType;

    @Schema(description = "列关键字")
    @TableField(value = "COLUMN_KEY")
    private String columnKey;

    @Schema(description = "附加的")
    @TableField(value = "EXTRA")
    private String extra;

    @Schema(description = "特权")
    @TableField(value = "PRIVILEGES")
    private String privileges;

    @Schema(description = "列注释")
    @TableField(value = "COLUMN_COMMENT")
    private String columnComment;

    @Schema(description = "生成表达式")
    @TableField(value = "GENERATION_EXPRESSION")
    private String generationExpression;

    @Schema(description = "srsId")
    @TableField(value = "SRS_ID")
    private Integer srsId;

    @Schema(description = "字段名")
    @TableField(exist = false)
    private String fieldName;

    @Schema(description = "字段类型")
    @TableField(exist = false)
    private String fieldType;

    @Schema(description = "是否主键")
    @TableField(exist = false)
    private Boolean isKey = false;
}
@Getter
@Setter
@TableName(value = "information_schema.TABLES")
@Schema(description = "MySql表信息")
public class MySqlTable implements Serializable {
    @Serial
    private static final long serialVersionUID = 42L;

    @Schema(description = "表目录")
    @TableField(value = "TABLE_CATALOG")
    private String tableCatalog;

    @Schema(description = "表架构")
    @TableField(value = "TABLE_SCHEMA")
    private String tableSchema;

    @Schema(description = "表名称")
    @TableField(value = "TABLE_NAME")
    private String tableName;

    @Schema(description = "表类型")
    @TableField(value = "TABLE_TYPE")
    private String tableType;

    @Schema(description = "引擎")
    @TableField(value = "ENGINE")
    private String engine;

    @Schema(description = "版本")
    @TableField(value = "VERSION")
    private Integer version;

    @Schema(description = "行格式")
    @TableField(value = "ROW_FORMAT")
    private String rowFormat;

    @Schema(description = "表格行")
    @TableField(value = "TABLE_ROWS")
    private Long tableRows;

    @Schema(description = "平均行长度")
    @TableField(value = "AVG_ROW_LENGTH")
    private Long avgRowLength;

    @Schema(description = "数据长度")
    @TableField(value = "DATA_LENGTH")
    private Long dataLength;

    @Schema(description = "最大数据长度")
    @TableField(value = "MAX_DATA_LENGTH")
    private Long maxDataLength;

    @Schema(description = "索引长度")
    @TableField(value = "INDEX_LENGTH")
    private Long indexLength;

    // 描述有误
    @Schema(description = "数据自由")
    @TableField(value = "DATA_FREE")
    private Long dataFree;

    @Schema(description = "自动增加")
    @TableField(value = "AUTO_INCREMENT")
    private Long autoIncrement;

    @Schema(description = "创建时间")
    @TableField(value = "CREATE_TIME")
    private LocalDateTime createTime;

    @Schema(description = "更新时间")
    @TableField(value = "UPDATE_TIME")
    private LocalDateTime updateTime;

    @Schema(description = "检查时间")
    @TableField(value = "CHECK_TIME")
    private LocalDateTime checkTime;

    @Schema(description = "表排序规则")
    @TableField(value = "TABLE_COLLATION")
    private String tableCollation;

    @Schema(description = "校验和")
    @TableField(value = "CHECKSUM")
    private Long checksum;

    @Schema(description = "创建选项")
    @TableField(value = "CREATE_OPTIONS")
    private String createOptions;

    @Schema(description = "表注释")
    @TableField(value = "TABLE_COMMENT")
    private String tableComment;

    @Schema(description = "类名")
    @TableField(exist = false)
    private String className;

    @Schema(description = "类访问")
    @TableField(exist = false)
    private String classAddress;

    @Schema(description = "主键字段类型")
    @TableField(exist = false)
    private String tableKeyFieldType;

    @Schema(description = "id不为空")
    @TableField(exist = false)
    private Boolean idNotNull = false;

    @Schema(description = "创建时间不为空")
    @TableField(exist = false)
    private Boolean createTimeNotNull = false;

    @Schema(description = "更新时间不为空")
    @TableField(exist = false)
    private Boolean updateTimeNotNull = false;

    @Schema(description = "创建人不为空")
    @TableField(exist = false)
    private Boolean createByNotNull = false;

    @Schema(description = "更新人不为空")
    @TableField(exist = false)
    private Boolean updateByNotNull = false;
}

mapper包:

@Mapper
public interface MySqlColumnMapper extends BaseMapper<MySqlColumn> {
}
@Mapper
public interface MySqlTableMapper extends BaseMapper<MySqlTable> {
}

service包

public interface MySqlCodeGeneratorService {

    /**
     * 代码生成Zip
     * @param outputStream Http响应对象
     * @param dto 代码生成对象
     */
    void codeGeneratorZip(ZipOutputStream outputStream, BatchCodeGenerateMySqlDto dto) throws IOException;
}
public interface MySqlColumnService extends IService<MySqlColumn> {
}
public interface MySqlTableService extends IService<MySqlTable> {
}

service.impl包:

@Slf4j
@Service
@AllArgsConstructor
public class MySqlCodeGeneratorServiceImpl implements MySqlCodeGeneratorService {

    private MySqlTableService tableService;
    private MySqlColumnService columnService;

    @Override
    public void codeGeneratorZip(ZipOutputStream outputStream, BatchCodeGenerateMySqlDto dto) throws IOException {

        String tableNamePrefix = dto.getTableNamePrefix();
        List<String> tableNameList = dto.getTableNameList();
        Map<MySqlTable, List<MySqlColumn>> tableToColumnMap = new HashMap<>();

        // 表信息
        List<MySqlTable> tableList = tableNameList.stream().map(it -> {
            String tableName = tableNamePrefix + it;
            Wrapper<MySqlTable> wrapper = new LambdaQueryWrapper<MySqlTable>()
                    .eq(MySqlTable::getTableSchema, dto.getTableSchema())
                    .eq(MySqlTable::getTableName, tableName);
            MySqlTable table = tableService.getOne(wrapper);
            table.setClassName(convertClassName(table.getTableName()));
            table.setClassAddress(StringUtils.uncapitalize(table.getClassName()));
            return table;
        }).toList();

        // 表与列对照信息
        tableList.forEach(table -> {
            Wrapper<MySqlColumn> wrapper = new LambdaQueryWrapper<MySqlColumn>()
                    .eq(MySqlColumn::getTableSchema, dto.getTableSchema())
                    .eq(MySqlColumn::getTableName, table.getTableName());
            List<MySqlColumn> list = columnService.list(wrapper);
            list.forEach(column -> {
                column.setFieldName(convertFieldName(column.getColumnName()));
                column.setFieldType(convertFieldTyp(column.getColumnType()));
                column.setIsKey(column.getColumnKey().equals("PRI"));
                if (column.getIsKey() && table.getTableKeyFieldType() == null) {
                    table.setTableKeyFieldType(column.getFieldType());
                }
                if (column.getColumnName().equals("id")) {
                    table.setIdNotNull(true);
                }
                if (column.getColumnName().equals("create_time")) {
                    table.setCreateTimeNotNull(true);
                }
                if (column.getColumnName().equals("update_time")) {
                    table.setUpdateTimeNotNull(true);
                }
                if (column.getColumnName().equals("create_by")) {
                    table.setCreateByNotNull(true);
                }
                if (column.getColumnName().equals("update_by")) {
                    table.setUpdateByNotNull(true);
                }
            });
            list.sort(Comparator.comparing(MySqlColumn::getOrdinalPosition));
            tableToColumnMap.put(table, list);
        });


        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        for (Map.Entry<MySqlTable, List<MySqlColumn>> mapEntry : tableToColumnMap.entrySet()) {
            Map<String, Object> templateMap = new HashMap<>();
            templateMap.put("packageAddress", dto.getPackageAddress());
            templateMap.put("author", dto.getAuthor());
            templateMap.put("dateTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            templateMap.put("table", mapEntry.getKey());
            templateMap.put("columnList", mapEntry.getValue());
            // 模板路径列表
            List<String> templatePathList = getTemplatePathList();
            // 上下文对象
            VelocityContext velocityContext = new VelocityContext(templateMap);
            for (String templatePath : templatePathList) {
                String filePath = getFilePath(templatePath, mapEntry.getKey().getClassName(), mapEntry.getKey().getClassAddress());
                Template template = Velocity.getTemplate(templatePath, "UTF-8");
                StringWriter sw = new StringWriter();
                template.merge(velocityContext, sw);
                outputStream.putNextEntry(new ZipEntry(filePath));
                IOUtils.write(sw.toString(), outputStream, "UTF-8");
                IOUtils.close(sw);
                outputStream.closeEntry();
            }
        }
    }

    /**
     * 转换类名
     *
     * @param tableName 表名称
     * @return 类名称
     */
    private String convertClassName(String tableName) {
        return CaseUtils.toCamelCase(tableName, true, '_');
    }

    /**
     * 转换字段名
     *
     * @param columnName 列名称
     * @return 字段名
     */
    private String convertFieldName(String columnName) {
        return CaseUtils.toCamelCase(columnName, false, '_');
    }

    /**
     * 获取字段类型
     *
     * @param columnType 列类型
     * @return 返回 JAVA 类型
     */
    private String convertFieldTyp(String columnType) {
        if (columnType.startsWith("char") || columnType.startsWith("varchar") || columnType.startsWith("tinytext") || columnType.startsWith("text") || columnType.startsWith("mediumtext") || columnType.startsWith("longtext")) {
            return "String";
        } else if (columnType.startsWith("bit(1") || columnType.startsWith("tinyint(1") || columnType.startsWith("boolean") || columnType.startsWith("bool")) {
            return "Boolean";
        } else if (columnType.startsWith("tinyint") || columnType.startsWith("int")) {
            return "Integer";
        } else if (columnType.startsWith("bigint")) {
            return "Long";
        } else if (columnType.startsWith("float")) {
            return "Float";
        } else if (columnType.startsWith("double")) {
            return "Double";
        } else if (columnType.startsWith("decimal")) {
            return "BigDecimal";
        } else if (columnType.startsWith("datetime") || columnType.startsWith("timestamp")) {
            return "LocalDateTime";
        } else if (columnType.startsWith("date")) {
            return "LocalDate";
        } else if (columnType.startsWith("time")) {
            return "LocalTime";
        } else {
            return "";
        }
    }

    /**
     * 模板路径地址列表
     *
     * @return 模板路径地址
     */
    private List<String> getTemplatePathList() {
        return List.of(
                "template/entity/Entity.java.vm",
                "template/dto/FindPageDto.java.vm",
                "template/dto/FindListDto.java.vm",
                "template/dto/SaveDto.java.vm",
                "template/dto/UpdateDto.java.vm",
                "template/dto/Vo.java.vm",
                "template/dao/Dao.java.vm",
                "template/dao/Dao.xml.vm",
                "template/service/Service.java.vm",
                "template/service/impl/ServiceImpl.java.vm",
                "template/controller/Controller.java.vm"
        );
    }

    private String getFilePath(String templatePath, String className, String dtoPackage) {
        // 分隔符
        String separator = File.separator;
        if (templatePath.endsWith("Entity.java.vm")) {
            return "code" + separator + "java" + separator + "entity" + separator + className + ".java";
        } else if (templatePath.endsWith("FindPageDto.java.vm")) {
            return "code" + separator + "java" + separator + "dto" + separator + dtoPackage + separator + className + "FindPageDto.java";
        } else if (templatePath.endsWith("FindListDto.java.vm")) {
            return "code" + separator + "java" + separator + "dto" + separator + dtoPackage + separator + className + "FindListDto.java";
        } else if (templatePath.endsWith("SaveDto.java.vm")) {
            return "code" + separator + "java" + separator + "dto" + separator + dtoPackage + separator + className + "SaveDto.java";
        } else if (templatePath.endsWith("UpdateDto.java.vm")) {
            return "code" + separator + "java" + separator + "dto" + separator + dtoPackage + separator + className + "UpdateDto.java";
        } else if (templatePath.endsWith("Vo.java.vm")) {
            return "code" + separator + "java" + separator + "dto" + separator + dtoPackage + separator + className + "Vo.java";
        } else if (templatePath.endsWith("Dao.java.vm")) {
            return "code" + separator + "java" + separator + "dao" + separator + className + "Dao.java";
        } else if (templatePath.endsWith("Dao.xml.vm")) {
            return "code" + separator + "java" + separator + "dao" + separator + className + "Dao.xml";
        } else if (templatePath.endsWith("Service.java.vm")) {
            return "code" + separator + "java" + separator + "service" + separator + className + "Service.java";
        } else if (templatePath.endsWith("ServiceImpl.java.vm")) {
            return "code" + separator + "java" + separator + "service" + separator + "impl" + separator + className + "ServiceImpl.java";
        } else if (templatePath.endsWith("Controller.java.vm")) {
            return "code" + separator + "java" + separator + "controller" + separator + className + "Controller.java";
        }
        return "";
    }
}
@Slf4j
@Service
public class MySqlColumnServiceImpl extends ServiceImpl<MySqlColumnMapper, MySqlColumn> implements MySqlColumnService {
}
@Slf4j
@Service
public class MySqlTableServiceImpl extends ServiceImpl<MySqlTableMapper, MySqlTable> implements MySqlTableService {
}

Resource目录下的模板引擎:
在这里插入图片描述
controller引擎模板:

package ${packageAddress}.controller;

import ${packageAddress}.dto.AjaxResult;
import ${packageAddress}.dto.${table.classAddress}.${table.className}FindPageDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}FindListDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}SaveDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}UpdateDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}Vo;
import ${packageAddress}.entity.${table.className};
import ${packageAddress}.service.${table.className}Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * ${table.tableComment}Controller
 *
 * @author ${author}
 * @date ${dateTime}
 */
@Slf4j
@Tag(name = "${table.tableComment}", description = "${table.tableComment}控制器")
@ResponseBody
@RestController
@RequestMapping("/${table.classAddress}")
@AllArgsConstructor
public class ${table.className}Controller {

    private ${table.className}Service service;

    @GetMapping("/{id}")
    @Operation(summary = "获取详情")
    public AjaxResult<${table.className}Vo> getById(@PathVariable ${table.tableKeyFieldType} id) {
        Optional<${table.className}> optional = service.getOptById(id);
        ${table.className} entity = optional.orElseThrow(() -> new RuntimeException("找不到数据"));
        return AjaxResult.success(service.toVo(entity));
    }

    @GetMapping("/list")
    @Operation(summary = "获取列表")
    public AjaxResult<List<${table.className}Vo>> list(${table.className}FindListDto dto) {
        List<${table.className}> list = service.findByList(dto);
        return AjaxResult.success(list.stream().map(service::toVo).toList());
    }

    @GetMapping("/page")
    @Operation(summary = "获取分页")
    public AjaxResult<IPage<${table.className}Vo>> page(@Validated ${table.className}FindPageDto dto) {
        IPage<${table.className}> page = service.findByPage(dto);
        IPage<${table.className}Vo> voPage = page.convert(service::toVo);
        return AjaxResult.success(voPage);
    }

    @PostMapping
    @Operation(summary = "新增保存")
    public AjaxResult<Void> save(@RequestBody @Validated ${table.className}SaveDto dto) {
        service.save(dto);
        return AjaxResult.success();
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新修改")
    public AjaxResult<Void> update(@PathVariable ${table.tableKeyFieldType} id, @RequestBody @Validated ${table.className}UpdateDto dto) {
        service.update(id, dto);
        return AjaxResult.success();
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除")
    public AjaxResult<Void> delete(@PathVariable ${table.tableKeyFieldType} id) {
        service.removeById(id);
        return AjaxResult.success();
    }

}

dao引擎模板:

package ${packageAddress}.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import ${packageAddress}.entity .${table.className};
import ${packageAddress}.dto.${table.classAddress}.${table.className}FindListDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}FindPageDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}UpdateDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}SaveDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}Vo;
import java.util.List;

/**
* ${table.tableComment}Mapper
*
* @author ${author}
* @date ${dateTime}
*/
@Mapper
public interface ${table.className}Dao extends BaseMapper<${table.className}> {

    /**
    * 根据查询对象查询列表
    * @param dto 查询对象
    * @return 结果
    */
    List<${table.className}> selectByList(@Param("dto") ${table.className}FindListDto dto);

    /**
    * 根据查询对象查询分页
    * @param dto 查询对象
    * @return 结果
    */
    Page<${table.className}> selectByPage(@Param("page") Page<${table.className}> page, @Param("dto") ${table.className}FindPageDto dto);
}
<?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="${packageAddress}.dao.${table.className}Dao">
    <resultMap id="BaseResultMap" type="${packageAddress}.entity.${table.className}">
#foreach($column in $columnList)
    #if($column.isKey)
        <id column="${column.columnName}" property="${column.fieldName}" />
    #else
        <result column="${column.columnName}" property="${column.fieldName}" />
    #end
#end
    </resultMap>

    <select id="selectByList" resultMap="BaseResultMap">
        SELECT
        #foreach($column in $columnList)
            #if($foreach.hasNext)
            t1.${column.columnName},
            #else
            t1.${column.columnName}
            #end
        #end
        FROM ${table.tableName} t1
        <where>
            #foreach($column in $columnList)
            #if($column.fieldType.equals("String"))
            <if test="dto.${column.fieldName} != null and dto.${column.fieldName} != ''">
            #else
            <if test="dto.${column.fieldName} != null">
            #end
                AND t1.${column.columnName} = #{dto.${column.fieldName}}
            </if>
            #end
        </where>
    </select>

    <select id="selectByPage" resultMap="BaseResultMap">
        SELECT
        #foreach($column in $columnList)
            #if($foreach.hasNext)
            t1.${column.columnName},
            #else
            t1.${column.columnName}
            #end
        #end
        FROM ${table.tableName} t1
        <where>
        #foreach($column in $columnList)
            #if($column.fieldType.equals("String"))
            <if test="dto.${column.fieldName} != null and dto.${column.fieldName} != ''">
            #else
            <if test="dto.${column.fieldName} != null">
            #end
                AND t1.${column.columnName} = #{dto.${column.fieldName}}
            </if>
        #end
        </where>
    </select>

</mapper>

dto模板引擎:

package ${packageAddress}.dto.${table.classAddress};

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import ${packageAddress}.entity.${table.className};
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.io.Serial;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;


/**
 * ${table.tableComment}查询列表DTO
 *
 * @author ${author}
 * @date ${dateTime}
 */

@Getter
@Setter
@Schema(description = "${table.tableComment}查询列表DTO")
public class ${table.className}FindListDto extends ${table.className} implements Serializable {
    @Serial
    private static final long serialVersionUID = 42L;

}
package ${packageAddress}.dto.${table.classAddress};

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import ${packageAddress}.entity.${table.className};
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.io.Serial;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;


/**
 * ${table.tableComment}查询分页DTO
 *
 * @author ${author}
 * @date ${dateTime}
 */

@Getter
@Setter
@Schema(description = "${table.tableComment}查询分页DTO")
public class ${table.className}FindPageDto extends ${table.className} implements Serializable {
    @Serial
    private static final long serialVersionUID = 42L;

    /**
     * 页码
     **/
    @NotNull(message = "页码不能为空")
    @Schema(description = "页码")
    private Long page;
    /**
     * 页数
     **/
    @NotNull(message = "页数不能为空")
    @Schema(description = "页数")
    private Long pageSize;

}
package ${packageAddress}.dto.${table.classAddress};

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.io.Serial;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;


/**
 * ${table.tableComment}新增保存DTO
 *
 * @author ${author}
 * @date ${dateTime}
 */

@Getter
@Setter
@Schema(description = "${table.tableComment}新增保存DTO")
public class ${table.className}SaveDto implements Serializable {
    @Serial
    private static final long serialVersionUID = 42L;

#foreach($column in $columnList)
#if($column.columnName.equals("id") || $column.columnName.equals("create_time") || $column.columnName.equals("update_time") || $column.columnName.equals("create_by") || $column.columnName.equals("update_by"))
#else
    #if($column.isNullable.equals("NO") && $column.fieldType.equals("String"))
    @NotBlank
    #elseif($column.isNullable.equals("NO"))
    @NotNull
    #end
    #if($column.fieldType.equals("LocalDateTime"))
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    #elseif($column.fieldType.equals("LocalDate"))
    @JsonFormat(pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    #elseif($column.fieldType.equals("LocalTime"))
    @JsonFormat(pattern = "HH:mm:ss")
    @DateTimeFormat(pattern = "HH:mm:ss")
    #end
    @Schema(description = "${column.columnComment}")
    private ${column.fieldType} ${column.fieldName};

#end
#end
}
package ${packageAddress}.dto.${table.classAddress};

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.io.Serial;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;


/**
 * ${table.tableComment}
 *
 * @author ${author}
 * @date ${dateTime}
 */

@Getter
@Setter
@Schema(description = "${table.tableComment}更新DTO")
public class ${table.className}UpdateDto implements Serializable {
    @Serial
    private static final long serialVersionUID = 42L;

#foreach($column in $columnList)

    #if($column.columnName.equals("id") || $column.columnName.equals("create_time") || $column.columnName.equals("update_time") || $column.columnName.equals("create_by") || $column.columnName.equals("update_by"))
    #else
    #if($column.fieldType.equals("LocalDateTime"))
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    #elseif($column.fieldType.equals("LocalDate"))
    @JsonFormat(pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    #elseif($column.fieldType.equals("LocalTime"))
    @JsonFormat(pattern = "HH:mm:ss")
    @DateTimeFormat(pattern = "HH:mm:ss")
    #end
    @Schema(description = "${column.columnComment}")
    private ${column.fieldType} ${column.fieldName};
    #end

#end
}
package ${packageAddress}.dto.${table.classAddress};

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.io.Serial;

import java.io.Serializable;
import ${packageAddress}.entity.${table.className};
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;


/**
 * ${table.tableComment}Vo
 *
 * @author ${author}
 * @date ${dateTime}
 */

@Getter
@Setter
@Schema(description = "${table.tableComment}视图Vo")
public class ${table.className}Vo extends ${table.className} implements Serializable {
    @Serial
    private static final long serialVersionUID = 42L;

}

entity模板引擎:

package ${packageAddress}.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
#if($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer") && ($table.createTimeNotNull == false || $table.updateTimeNotNull == false) && ($table.createByNotNull == false || $table.updateByNotNull == false))
import ${packageAddress}.entity.IdEntity;
#elseif($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer") && $table.createTimeNotNull == true && $table.updateTimeNotNull == true && ($table.createByNotNull == false || $table.updateByNotNull == false))
import ${packageAddress}.entity.DateTimeEntity;
#elseif($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer") && $table.createTimeNotNull == true && $table.updateTimeNotNull == true && $table.createByNotNull == true && $table.updateByNotNull == true)
import ${packageAddress}.entity.BaseEntity;
#else
import java.io.Serializable;
#end
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serial;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;


/**
 * ${table.tableComment}
 *
 * @author ${author}
 * @date ${dateTime}
 */

@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@TableName(value = "${table.tableName}")
@Schema(description = "${table.tableComment}")
#if($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer") && ($table.createTimeNotNull == false || $table.updateTimeNotNull == false) && ($table.createByNotNull == false || $table.updateByNotNull == false))
public class ${table.className} extends IdEntity {
#elseif($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer") && $table.createTimeNotNull == true && $table.updateTimeNotNull == true && ($table.createByNotNull == false || $table.updateByNotNull == false))
public class ${table.className} extends DateTimeEntity {
#elseif($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer") && $table.createTimeNotNull == true && $table.updateTimeNotNull == true && $table.createByNotNull == true && $table.updateByNotNull == true)
public class ${table.className} extends BaseEntity {
#else
public class ${table.className} implements Serializable {
#end

    @Serial
    private static final long serialVersionUID = 42L;

#if($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer")  && ($table.createTimeNotNull == false || $table.updateTimeNotNull == false) && ($table.createByNotNull == false || $table.updateByNotNull == false))
#foreach($column in $columnList)
    #if($column.columnName.equals("id") || $column.columnName.equals("create_time") || $column.columnName.equals("update_time"))
    #else
    #if($column.isNullable.equals("NO") && $column.fieldType.equals("String"))
    @NotBlank
    #elseif($column.isNullable.equals("NO"))
    @NotNull
    #end
    #if($column.isKey)
    @TableId(value = "${column.columnName}",type = IdType.AUTO;)
    #else
    @TableField(value = "${column.columnName}")
    #end#if($column.fieldType.equals("LocalDateTime"))
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    #elseif($column.fieldType.equals("LocalDate"))
    @JsonFormat(pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    #elseif($column.fieldType.equals("LocalTime"))
    @JsonFormat(pattern = "HH:mm:ss")
    @DateTimeFormat(pattern = "HH:mm:ss")
    #end
    @Schema(description = "${column.columnComment}")
    private ${column.fieldType} ${column.fieldName};
    #end

#end
#elseif($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer")  && $table.createTimeNotNull == true && $table.updateTimeNotNull == true && ($table.createByNotNull == false || $table.updateByNotNull == false))
#foreach($column in $columnList)
    #if($column.columnName.equals("id") || $column.columnName.equals("create_time") || $column.columnName.equals("update_time"))
    #else
    #if($column.isNullable.equals("NO") && $column.fieldType.equals("String"))
    @NotBlank
    #elseif($column.isNullable.equals("NO"))
    @NotNull
    #end
    #if($column.isKey)
    @TableId(value = "${column.columnName}",type = IdType.AUTO;)
    #else
    @TableField(value = "${column.columnName}")
    #end
    #if($column.fieldType.equals("LocalDateTime"))
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    #elseif($column.fieldType.equals("LocalDate"))
    @JsonFormat(pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    #elseif($column.fieldType.equals("LocalTime"))
    @JsonFormat(pattern = "HH:mm:ss")
    @DateTimeFormat(pattern = "HH:mm:ss")
    #end
    @Schema(description = "${column.columnComment}")
    private ${column.fieldType} ${column.fieldName};
    #end

#end
#elseif($table.idNotNull == true && $table.tableKeyFieldType.equals("Integer")  && $table.createTimeNotNull == true && $table.updateTimeNotNull == true && $table.createByNotNull == true && $table.updateByNotNull == true)
#foreach($column in $columnList)
    #if($column.columnName.equals("id") || $column.columnName.equals("create_time") || $column.columnName.equals("update_time") || $column.columnName.equals("create_by") || $column.columnName.equals("update_by"))
    #else
    #if($column.isNullable.equals("NO") && $column.fieldType.equals("String"))
    @NotBlank
    #elseif($column.isNullable.equals("NO"))
    @NotNull
    #end
    #if($column.isKey)
    @TableId(value = "${column.columnName}",type = IdType.AUTO;)
    #else
    @TableField(value = "${column.columnName}")
    #end
    #if($column.fieldType.equals("LocalDateTime"))
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    #elseif($column.fieldType.equals("LocalDate"))
    @JsonFormat(pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    #elseif($column.fieldType.equals("LocalTime"))
    @JsonFormat(pattern = "HH:mm:ss")
    @DateTimeFormat(pattern = "HH:mm:ss")
    #end
    @Schema(description = "${column.columnComment}")
    private ${column.fieldType} ${column.fieldName};
    #end

#end
#else
#foreach($column in $columnList)
    #if($column.isNullable.equals("NO") && $column.fieldType.equals("String"))
    @NotBlank
    #elseif($column.isNullable.equals("NO"))
    @NotNull
    #end
    #if($column.isKey)
    @TableId(value = "${column.columnName}",type = IdType.AUTO)
    #else
    @TableField(value = "${column.columnName}")
    #end
    #if($column.fieldType.equals("LocalDateTime"))
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    #elseif($column.fieldType.equals("LocalDate"))
    @JsonFormat(pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    #elseif($column.fieldType.equals("LocalTime"))
    @JsonFormat(pattern = "HH:mm:ss")
    @DateTimeFormat(pattern = "HH:mm:ss")
    #end
    @Schema(description = "${column.columnComment}")
    private ${column.fieldType} ${column.fieldName};

#end
#end

}

service模板引擎:

package ${packageAddress}.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import ${packageAddress}.entity.${table.className};
import ${packageAddress}.dto.${table.classAddress}.${table.className}FindPageDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}FindListDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}UpdateDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}SaveDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}Vo;

import java.util.List;
import java.util.Optional;

/**
 * ${table.tableComment}Service
 *
 * @author ${author}
 * @date ${dateTime}
 */
public interface ${table.className}Service extends IService<${table.className}> {

    /**
     * 按列表查询
     *
     * @param dto 查询对象
     */
    List<${table.className}> findByList(${table.className}FindListDto dto);

    /**
     * 按分页查询
     *
     * @param dto 查询对象
     */
    Page<${table.className}> findByPage(${table.className}FindPageDto dto);

    /**
     * 新增一条数据
     *
     * @param dto 新增对象
     */
    void save(${table.className}SaveDto dto);

    /**
     * 更新一条数据
     *
     * @param id id
     * @param dto 新增对象
     */
    void update(${table.tableKeyFieldType} id, ${table.className}UpdateDto dto);

    /**
     * 转换为Vo对象
     *
     * @param entity 实体
     */
    ${table.className}Vo toVo(${table.className} entity);

}

service.impl模板引擎:

package ${packageAddress}.service.impl;

import ${packageAddress}.dto.${table.classAddress}.${table.className}FindPageDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}FindListDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}UpdateDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}SaveDto;
import ${packageAddress}.dto.${table.classAddress}.${table.className}Vo;
import ${packageAddress}.entity.${table.className};
import ${packageAddress}.dao.${table.className}Dao;
import ${packageAddress}.service.${table.className}Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * ${table.tableComment}Service
 *
 * @author ${author}
 * @date ${dateTime}
 */
@Slf4j
@Service
@Primary
public class ${table.className}ServiceImpl extends ServiceImpl<${table.className}Dao, ${table.className}> implements ${table.className}Service {

    @Override
    public List<${table.className}> findByList(${table.className}FindListDto dto) {
        return baseMapper.selectByList(dto);
    }

    @Override
    public Page<${table.className}> findByPage(${table.className}FindPageDto dto) {
        Page<${table.className}> page = new Page<>(dto.getPage(), dto.getPageSize());
        return baseMapper.selectByPage(page, dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(${table.className}SaveDto dto) {
        ${table.className} entity = new ${table.className}();
        BeanUtils.copyProperties(dto, entity);
        baseMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(${table.tableKeyFieldType} id, ${table.className}UpdateDto dto) {
        Optional<${table.className}> entityOpt = getOptById(id);
        ${table.className} entity = entityOpt.orElseThrow(() -> new RuntimeException("找不到数据"));
        BeanUtils.copyProperties(entity, dto);
        baseMapper.updateById(entity);
    }

    @Override
    public ${table.className}Vo toVo(${table.className} entity) {
        ${table.className}Vo vo = new ${table.className}Vo();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }
}

结果:
在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_46649945/article/details/140549193

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!