刚入职没多久,连夜手写了一个代码生成器,项目开发速度瞬间屌炸了!(一)

简介: 各位网友,大家好,我是阿粉!最近刚入职一个新团队,还没来得及熟悉业务,甲方爸爸就要求项目要在2个月内完成开发并上线!本想着往后推迟1个月在交付,但是甲方爸爸不同意,只能赶鸭子上架了!然后根据业务需求,设计出了大概30多张表,如果这30多张表,全靠开发人员手写 crud,开发所需的时间肯定会大大的延长,甚至可能直接会影响交付时间!于是就想着,能不能通过代码生成器一键搞定全部的 crud,开发团队只需要根据业务需求编写逻辑代码就可以?

一、简介

各位网友,大家好,我是阿粉!

最近刚入职一个新团队,还没来得及熟悉业务,甲方爸爸就要求项目要在2个月内完成开发并上线!

本想着往后推迟1个月在交付,但是甲方爸爸不同意,只能赶鸭子上架了!

然后根据业务需求,设计出了大概30多张表,如果这30多张表,全靠开发人员手写 crud,开发所需的时间肯定会大大的延长,甚至可能直接会影响交付时间!

于是就想着,能不能通过代码生成器一键搞定全部的 crud,开发团队只需要根据业务需求编写逻辑代码就可以?

本来计划是用mybatis-plus的,但是生成的代码,根据现有的框架标准,很多代码也需要自己改,有些地方还不如自己手写用的舒服,因此就决定手写一套代码生成器!

很多新手会觉得代码生成器很个高深的东西。其实不然,一点都不高深,当你看完本文的时候,你会完全掌握代码生成器的逻辑,甚至可以根据自己的项目情况,进行深度定制。

废话也不多说了,直接代码撸上!

二、实现思路

下面我就以SpringBoot项目为例,数据持久化操作采用Mybatis,数据库采用Mysql,编写一个自动生成增、删、改、查等基础功能的代码生成器,内容包括controller、service、dao、entity、dto、vo等信息。

实现思路如下:

  • 第一步:获取表字段名称、类型、表注释等信息
  • 第二步:基于 freemarker 模板引擎,编写相应的模板
  • 第三步:根据对应的模板,生成相应的 java 代码

2.1、获取表结构

首先我们创建一张test_db表,脚本如下:

CREATE TABLE test_db (
  id bigint(20) unsigned NOT NULL COMMENT '主键ID',
  name varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '名称',
  is_delete tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除 1:已删除;0:未删除',
  create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (id),
  KEY idx_create_time (create_time) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='测试表';

表创建完成之后,基于test_db表,我们查询对应的表结果字段名称、类型、备注信息,这些信息收集将用于后续进行代码生成器所使用!

# 获取对应表结构
SELECT column_name, data_type, column_comment FROM information_sc

0.jpg


同时,获取对应表注释,用于生成备注信息!

# 获取对应表注释
SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE table_sc


1.jpg

2.2、编写模板

  • 编写mapper模板,涵盖新增、修改、删除、查询等信息
<?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="${daoPackageName}.${daoName}">
 <!--BaseResultMap-->
 <resultMap id="BaseResultMap" type="${entityPackageName}.${entityName}">
        <#list columns as pro>
            <#if pro.proName == primaryId>
    <id column="${primaryId}" property="${primaryId}" jdbcType="${pro.fieldType}"/>
            <#else>
    <result column="${pro.fieldName}" property="${pro.proName}" jdbcType="${pro.fieldType}"/>
            </#if>
        </#list>
 </resultMap>
 <!--Base_Column_List-->
 <sql id="Base_Column_List">
        <#list columns as pro>
            <#if pro_index == 0>${pro.fieldName}<#else>,${pro.fieldName}</#if>
        </#list>
 </sql>
 <!--批量插入-->
 <insert id="insertList" parameterType="java.util.List">
  insert into ${tableName} (
        <#list columns as pro>
            <#if pro_index == 0>${pro.fieldName},<#elseif pro_index == 1>${pro.fieldName}<#else>,${pro.fieldName}</#if>
        </#list>
  )
  values
  <foreach collection ="list" item="obj" separator =",">
   <trim prefix=" (" suffix=")" suffixOverrides=",">
                <#list columns as pro>
                    ${r"#{obj." + pro.proName + r"}"},
                </#list>
   </trim>
  </foreach >
 </insert>
 <!--按需新增-->
 <insert id="insertPrimaryKeySelective" parameterType="${entityPackageName}.${entityName}">
  insert into ${tableName}
  <trim prefix="(" suffix=")" suffixOverrides=",">
            <#list columns as pro>
    <if test="${pro.proName} != null">
                    ${pro.fieldName},
    </if>
            </#list>
  </trim>
  <trim prefix="values (" suffix=")" suffixOverrides=",">
            <#list columns as pro>
    <if test="${pro.proName} != null">
                    ${r"#{" + pro.proName + r",jdbcType=" + pro.fieldType +r"}"},
    </if>
            </#list>
  </trim>
 </insert>
 <!-- 按需修改-->
 <update id="updatePrimaryKeySelective" parameterType="${entityPackageName}.${entityName}">
  update ${tableName}
  <set>
            <#list columns as pro>
                <#if pro.fieldName != primaryId && pro.fieldName != primaryId>
     <if test="${pro.proName} != null">
                        ${pro.fieldName} = ${r"#{" + pro.proName + r",jdbcType=" + pro.fieldType +r"}"},
     </if>
                </#if>
            </#list>
  </set>
  where ${primaryId} = ${r"#{" + "${primaryId}" + r",jdbcType=BIGINT}"}
 </update>
 <!-- 按需批量修改-->
 <update id="updateBatchByIds" parameterType="java.util.List">
  update ${tableName}
  <trim prefix="set" suffixOverrides=",">
            <#list columns as pro>
                <#if pro.fieldName != primaryId && pro.fieldName != primaryId>
     <trim prefix="${pro.fieldName}=case" suffix="end,">
      <foreach collection="list" item="obj" index="index">
       <if test="obj.${pro.proName} != null">
        when id = ${r"#{" + "obj.id" + r"}"}
        then  ${r"#{obj." + pro.proName + r",jdbcType=" + pro.fieldType +r"}"}
       </if>
      </foreach>
     </trim>
                </#if>
            </#list>
  </trim>
  where
  <foreach collection="list" separator="or" item="obj" index="index" >
   id = ${r"#{" + "obj.id" + r"}"}
  </foreach>
 </update>
 <!-- 删除-->
 <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
  delete from ${tableName}
  where ${primaryId} = ${r"#{" + "${primaryId}" + r",jdbcType=BIGINT}"}
 </delete>
 <!-- 查询详情 -->
 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long">
  select
  <include refid="Base_Column_List"/>
  from ${tableName}
  where ${primaryId} = ${r"#{" + "${primaryId}" + r",jdbcType=BIGINT}"}
 </select>
 <!-- 按需查询 -->
 <select id="selectByPrimaryKeySelective" resultMap="BaseResultMap" parameterType="${entityPackageName}.${entityName}">
  select
  <include refid="Base_Column_List"/>
  from ${tableName}
 </select>
 <!-- 批量查询-->
 <select id="selectByIds" resultMap="BaseResultMap" parameterType="java.util.List">
  select
  <include refid="Base_Column_List"/>
  from ${tableName}
  <where>
   <if test="ids != null">
    and ${primaryId} in
    <foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
                    ${r"#{" + "item" + r"}"}
    </foreach>
   </if>
  </where>
 </select>
 <!-- 根据条件查询 -->
 <select id="selectByMap" resultMap="BaseResultMap" parameterType="java.util.Map">
  select
  <include refid="Base_Column_List"/>
  from ${tableName}
 </select>
 <!-- 查询${entityName}总和 -->
 <select id="countPage" resultType="int" parameterType="${dtoPackageName}.${dtoName}">
  select count(${primaryId})
  from ${tableName}
 </select>
 <!-- 查询${entityName}列表 -->
 <select id="selectPage" resultMap="BaseResultMap" parameterType="${dtoPackageName}.${dtoName}">
  select
  <include refid="Base_Column_List"/>
  from ${tableName}
  limit ${r"#{" + "start,jdbcType=INTEGER" + r"}"},${r"#{" + "end,jdbcType=INTEGER" + r"}"}
 </select>
</mapper>
  • 编写dao数据访问模板
package ${daoPackageName};
import com.example.generator.core.BaseMapper;
import java.util.List;
import ${entityPackageName}.${entityName};
import ${dtoPackageName}.${dtoName};
/**
*
* @ClassName: ${daoName}
* @Description: 数据访问接口
* @author ${authorName}
* @date ${currentTime}
*
*/
public interface ${daoName} extends BaseMapper<${entityName}>{
 int countPage(${dtoName} ${dtoName?uncap_first});
 List<${entityName}> selectPage(${dtoName} ${dtoName?uncap_first});
}
  • 编写service服务接口模板
package ${servicePackageName};
import com.example.generator.core.BaseService;
import com.example.generator.common.Pager;
import ${voPackageName}.${voName};
import ${dtoPackageName}.${dtoName};
import ${entityPackageName}.${entityName};
/**
 *
 * @ClassName: ${serviceName}
 * @Description: ${entityName}业务访问接口
 * @author ${authorName}
 * @date ${currentTime}
 *
 */
public interface ${serviceName} extends BaseService<${entityName}> {
 /**
  * 分页列表查询
  * @param request
  */
 Pager<${voName}> getPage(${dtoName} request);
}
  • 编写serviceImpl服务实现类模板
package ${serviceImplPackageName};
import com.example.generator.common.Pager;
import com.example.generator.core.BaseServiceImpl;
import com.example.generator.test.service.TestEntityService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import ${daoPackageName}.${daoName};
import ${entityPackageName}.${entityName};
import ${dtoPackageName}.${dtoName};
import ${voPackageName}.${voName};
@Service
public class ${serviceImplName} extends BaseServiceImpl<${daoName}, ${entityName}> implements ${serviceName} {
 private static final Logger log = LoggerFactory.getLogger(${serviceImplName}.class);
 /**
  * 分页列表查询
  * @param request
  */
 public Pager<${voName}> getPage(${dtoName} request) {
  List<${voName}> resultList = new ArrayList();
  int count = super.baseMapper.countPage(request);
  List<${entityName}> dbList = count > 0 ? super.baseMapper.selectPage(request) : new ArrayList<>();
  if(!CollectionUtils.isEmpty(dbList)){
   dbList.forEach(source->{
    ${voName} target = new ${voName}();
    BeanUtils.copyProperties(source, target);
    resultList.add(target);
   });
  }
  return new Pager(request.getCurrPage(), request.getPageSize(), count, resultList);
 }
}
  • 编写controller控制层模板
package ${controllerPackageName};
import com.example.generator.common.IdRequest;
import com.example.generator.common.Pager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Objects;
import ${servicePackageName}.${serviceName};
import ${entityPackageName}.${entityName};
import ${dtoPackageName}.${dtoName};
import ${voPackageName}.${voName};
/**
 *
 * @ClassName: ${controllerName}
 * @Description: 外部访问接口
 * @author ${authorName}
 * @date ${currentTime}
 *
 */
@RestController
@RequestMapping("/${entityName?uncap_first}")
public class ${controllerName} {
 @Autowired
 private ${serviceName} ${serviceName?uncap_first};
 /**
  * 分页列表查询
  * @param request
  */
 @PostMapping(value = "/getPage")
 public Pager<${voName}> getPage(@RequestBody ${dtoName} request){
  return ${serviceName?uncap_first}.getPage(request);
 }
 /**
  * 查询详情
  * @param request
  */
 @PostMapping(value = "/getDetail")
 public ${voName} getDetail(@RequestBody IdRequest request){
  ${entityName} source = ${serviceName?uncap_first}.selectById(request.getId());
  if(Objects.nonNull(source)){
   ${voName} result = new ${voName}();
   BeanUtils.copyProperties(source, result);
   return result;
  }
  return null;
 }
 /**
  * 新增操作
  * @param request
  */
 @PostMapping(value = "/save")
 public void save(${dtoName} request){
  ${entityName} entity = new ${entityName}();
  BeanUtils.copyProperties(request, entity);
  ${serviceName?uncap_first}.insert(entity);
 }
 /**
  * 编辑操作
  * @param request
  */
 @PostMapping(value = "/edit")
 public void edit(${dtoName} request){
  ${entityName} entity = new ${entityName}();
  BeanUtils.copyProperties(request, entity);
  ${serviceName?uncap_first}.updateById(entity);
 }
 /**
  * 删除操作
  * @param request
  */
 @PostMapping(value = "/delete")
 public void delete(IdRequest request){
  ${serviceName?uncap_first}.deleteById(request.getId());
 }
}
  • 编写entity实体类模板
package ${entityPackageName};
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
 *
 * @ClassName: ${entityName}
 * @Description: ${tableDes!}实体类
 * @author ${authorName}
 * @date ${currentTime}
 *
 */
public class ${entityName} implements Serializable {
 private static final long serialVersionUID = 1L;
 <#--属性遍历-->
 <#list columns as pro>
 <#--<#if pro.proName != primaryId
 && pro.proName != 'remarks'
 && pro.proName != 'createBy'
 && pro.proName != 'createDate'
 && pro.proName != 'updateBy'
 && pro.proName != 'updateDate'
 && pro.proName != 'delFlag'
 && pro.proName != 'currentUser'
 && pro.proName != 'page'
 && pro.proName != 'sqlMap'
 && pro.proName != 'isNewRecord'
 ></#if>-->
 /**
  * ${pro.proDes!}
  */
 private ${pro.proType} ${pro.proName};
 </#list>
 <#--属性get||set方法-->
 <#list columns as pro>
 public ${pro.proType} get${pro.proName?cap_first}() {
  return this.${pro.proName};
 }
 public ${entityName} set${pro.proName?cap_first}(${pro.proType} ${pro.proName}) {
  this.${pro.proName} = ${pro.proName};
  return this;
 }
 </#list>
}
  • 编写dto实体类模板
package ${dtoPackageName};
import com.example.generator.core.BaseDTO;
import java.io.Serializable;
/**
 * @ClassName: ${dtoName}
 * @Description: 请求实体类
 * @author ${authorName}
 * @date ${currentTime}
 *
 */
public class ${dtoName} extends BaseDTO {
}
相关文章
|
安全 Linux 数据安全/隐私保护
Intel TME和MKTME技术解析
# 市场需求 人们对透明全内存加密这个功能的需求主要来自对机密和敏感数据的保护。普通RAM里面储存的数据,在掉电之后,一般都以为是彻底消失了。但其实在一些复杂的离线攻击下,这些数据仍然是能被恢复出来并导致泄密;而持久性存储器(即外存,包括磁盘、SSD、eMMC等)的数据更加容易泄露。这些设备可能有硬件锁机制的保护,但是用户其实希望的是更细粒度的保护,比如per进程/容器/VM级的。 Int
6576 0
Intel TME和MKTME技术解析
|
12月前
|
传感器 人工智能 边缘计算
宠物识别算法在智能猫窝上的应用:区域预警、Vlog生成与睡眠监测一体化方案
基于边缘计算与多传感器融合,智能猫窝集成宠物识别算法,实现区域预警、Vlog自动生成与睡眠监测一体化。通过AI视觉、毫米波雷达等技术,精准识别宠物行为,助力远程看护与健康管理,提升人宠情感连接,打造智慧养宠新体验。
982 1
|
6月前
|
人工智能 监控 搜索推荐
同名混淆检测与结构化内容策略:个人GEO实验的系统架构实践
本文介绍“黄小宇”个人GEO实验:针对大模型同名混淆问题(如误认画家),构建可量化检测—归因—治理系统,通过结构化内容策略提升AI对真实身份的认知精度,探索AI时代个体可见度的科学建设路径。(239字)
|
8月前
|
人工智能 自然语言处理 监控
《QClaw重构开发的四个底层逻辑,看懂少走半年弯路》
本文直击传统开发自动化“维护工具比省时间还多”的普遍痛点,深度剖析QClaw与普通对话式AI的本质差异——它是具备本地系统级执行能力的智能体,而非简单的聊天助手。文章结合真实使用经验,分享了串联原子能力构建完整工作流、利用事件驱动搭建全自动开发环境、远程异步处理碎片化任务、引导智能体个性化适配四个核心实践,提出未来程序员将从代码编写者转变为智能体训练师的核心观点,为技术从业者重构开发流程提供了可落地的新思路。
527 0
|
11月前
|
NoSQL MongoDB 数据安全/隐私保护
基于 Docker 的 MongoDB 部署与使用指南
本指南面向不同层级开发者,详解 MongoDB 6.0 + Docker 部署:从单节点开发环境到高可用副本集生产部署,涵盖初始化、备份恢复、安全认证、监控告警及常见问题排查,助力高效构建稳定可靠的 MongoDB 服务。
1053 1
|
12月前
|
运维 监控 安全
一文读懂设备管理系统是什么?哪些企业适合使用?
设备管理系统通过数字化手段实现设备全生命周期管控,覆盖采购、使用、维护到报废各环节,助力企业实现状态可视、维护可控、成本可算、资源可用,提升管理效率与合规性。
|
机器学习/深度学习 人工智能 SDN
《重塑数据中心网络架构,迎接人工智能算力浪潮》
在人工智能快速发展的背景下,数据中心作为算力核心,其网络架构优化至关重要。传统三层架构因延迟高、扩展性差已难以满足AI需求。叶脊架构通过扁平化设计减少延迟并提升扩展性,高速网络技术(如100Gbps/400Gbps以太网)提供更大带宽,SDN与网络虚拟化实现灵活资源分配,优化流量管理进一步提高效率。未来,量子通信和边缘计算等技术将推动数据中心网络持续演进,助力AI算力提升,为社会带来更多变革。
1041 9
|
Linux Windows
怎么看电脑是32位还是64位
在使用电脑的时候,我们尝尝会听到“32位”和“64位”这两个术语,那么如何确定自己电脑是32位还是64位呢?本文将详细介绍几种简单的方法来帮助你了解你的电脑架构。
怎么看电脑是32位还是64位
|
人工智能 自然语言处理 数据管理
Step By Step 体验10 分钟在公众号和企微中构建自己的AI客服
为提升用户体验与竞争力,企业纷纷构建AI助手实现7x24小时客户服务。在阿里云平台上,仅需十分钟即可完成AI助手的搭建并发布至微信公众号或企业微信。流程包括创建大模型应用、引入AI助手至微信平台、导入私有知识以增强功能,以及将助手集成至企业微信中。此方案操作简便,文档详尽,可快速打造专属AI助手。但现有方案在错误提示、知识库构建指导及部署流程简化方面仍有待改进。
|
Shell Linux API
C语言在linux环境下执行终端命令
本文介绍了在Linux环境下使用C语言执行终端命令的方法。首先,文章描述了`system()`函数,其可以直接执行shell命令并返回结果。接着介绍了更强大的`popen()`函数,它允许程序与命令行命令交互,并详细说明了如何使用此函数及其配套的`pclose()`函数。此外,还讲解了`fork()`和`exec`系列函数,前者创建新进程,后者替换当前进程执行文件。最后,对比了`system()`与`exec`系列函数的区别,并针对不同场景推荐了合适的函数选择。