日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯網營銷解決方案
你還在手寫crud嗎,看完這篇文章,絕對賺了

本文轉載自微信公眾號「Java極客技術」,作者鴨血粉絲 。轉載本文請聯系Java極客技術公眾號。

成都創(chuàng)新互聯服務項目包括南樂網站建設、南樂網站制作、南樂網頁制作以及南樂網絡營銷策劃等。多年來,我們專注于互聯網行業(yè),利用自身積累的技術優(yōu)勢、行業(yè)經驗、深度合作伙伴關系等,向廣大中小型企業(yè)、政府機構等提供互聯網行業(yè)的解決方案,南樂網站推廣取得了明顯的社會效益與經濟效益。目前,我們服務的客戶以成都為中心已經輻射到南樂省份的部分城市,未來相信會繼續(xù)擴大服務區(qū)域并繼續(xù)獲得客戶的支持與信任!

一、介紹

我記得最早剛步入互聯網行業(yè)的時候,當時按照 MVC 的思想和模型,每次開發(fā)新功能,會依次編寫 dao、service、controller相關服務類,包括對應的 dto、entity、vo 等等實體類,如果有多張單表,也會重復的編寫相似的代碼,現在回想起來,感覺當時自己好像處于石器時代!

實際上,當仔細的總結一下,對于任何一張單表的操作,基本都是圍繞增(Create )、刪(Delete )、改(Update )、查(Retrieve )四個方向進行數據操作,簡稱 CRUD!

他們除了表名和存儲空間不一樣,基本的 CRUD 思路基本都是一樣的。

為了解決這些重復勞動的痛點,業(yè)界逐漸開源了一批代碼生成器,目的也很簡單,就是為了減少手工操作的繁瑣,集中精力在業(yè)務開發(fā)上,提升開發(fā)效率。

而今天,我們所要介紹的也是代碼生成器,很多初學者可能覺得代碼生成器很高深。代碼生成器其實是一個很簡單的東西,一點都不高深。

當你看完本文的時候,你會完全掌握代碼生成器的邏輯,甚至可以根據自己的項目情況,進行深度定制。

二、實現思路

下面我們就以SpringBoot項目為例,數據持久化操作采用Mybatis,數據庫采用Mysql,編寫一個自動生成增、刪、改、查等基礎功能的代碼生成器,內容包括controller、service、dao、entity、dto、vo等信息。

實現思路如下:

第一步:獲取表字段名稱、類型、表注釋等信息

第二步:基于 freemarker 模板引擎,編寫相應的模板

第三步:根據對應的模板,生成相應的 java 代碼

2.1、獲取表結構

首先我們創(chuàng)建一張test_db表,腳本如下:

 
 
 
 
  1. CREATE TABLE test_db (
  2.   id bigint(20) unsigned NOT NULL COMMENT '主鍵ID',
  3.   name varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '名稱',
  4.   is_delete tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否刪除 1:已刪除;0:未刪除',
  5.   create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時間',
  6.   update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',
  7.   PRIMARY KEY (id),
  8.   KEY idx_create_time (create_time) USING BTREE
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='測試表';

表創(chuàng)建完成之后,基于test_db表,我們查詢對應的表結果字段名稱、類型、備注信息,這些關鍵信息將用于后續(xù)進行代碼生成器所使用!

 
 
 
 
  1. # 獲取對應表結構
  2. SELECT column_name, data_type, column_comment FROM information_schema.columns WHERE table_schema = 'yjgj_base' AND table_name = 'test_db'

同時,獲取對應表注釋,用于生成備注信息!

 
 
 
 
  1. # 獲取對應表注釋
  2. SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'yjgj_base' AND table_name = 'test_db'

2.2、編寫模板

編寫mapper.ftl模板,涵蓋新增、修改、刪除、查詢等信息

 
 
 
 
  1.  
  2.  
  3.         <#list columns as pro>
  4.             <#if pro.proName == primaryId>
  5.     
  6.             <#else>
  7.     
  8.             
  9.         
  10.  
  11.  
  12.  
  13.         <#list columns as pro>
  14.             <#if pro_index == 0>${pro.fieldName}<#else>,${pro.fieldName}
  15.         
  16.  
  17.  
  18.  
  19.   insert into ${tableName} (
  20.         <#list columns as pro>
  21.             <#if pro_index == 0>${pro.fieldName},<#elseif pro_index == 1>${pro.fieldName}<#else>,${pro.fieldName}
  22.         
  23.   )
  24.   values
  25.   
  26.    
  27.                 <#list columns as pro>
  28.                     ${r"#{obj." + pro.proName + r"}"},
  29.                 
  30.    
  31.   
  32.  
  33.  
  34.  
  35.   insert into ${tableName}
  36.   
  37.             <#list columns as pro>
  38.     
  39.                     ${pro.fieldName},
  40.     
  41.             
  42.   
  43.   
  44.             <#list columns as pro>
  45.     
  46.                     ${r"#{" + pro.proName + r",jdbcType=" + pro.fieldType +r"}"},
  47.     
  48.             
  49.   
  50.  
  51.  
  52.  
  53.   update ${tableName}
  54.   
  55.             <#list columns as pro>
  56.                 <#if pro.fieldName != primaryId && pro.fieldName != primaryId>
  57.      
  58.                         ${pro.fieldName} = ${r"#{" + pro.proName + r",jdbcType=" + pro.fieldType +r"}"},
  59.      
  60.                 
  61.             
  62.   
  63.   where ${primaryId} = ${r"#{" + "${primaryId}" + r",jdbcType=BIGINT}"}
  64.  
  65.  
  66.  
  67.   update ${tableName}
  68.   
  69.             <#list columns as pro>
  70.                 <#if pro.fieldName != primaryId && pro.fieldName != primaryId>
  71.      
  72.       
  73.        
  74.         when id = ${r"#{" + "obj.id" + r"}"}
  75.         then  ${r"#{obj." + pro.proName + r",jdbcType=" + pro.fieldType +r"}"}
  76.        
  77.       
  78.      
  79.                 
  80.             
  81.   
  82.   where
  83.   
  84.    id = ${r"#{" + "obj.id" + r"}"}
  85.   
  86.  
  87.  
  88.  
  89.   delete from ${tableName}
  90.   where ${primaryId} = ${r"#{" + "${primaryId}" + r",jdbcType=BIGINT}"}
  91.  
  92.  
  93.  
  94.   select
  95.   
  96.   from ${tableName}
  97.   where ${primaryId} = ${r"#{" + "${primaryId}" + r",jdbcType=BIGINT}"}
  98.  
  99.  
  100.  
  101.   select
  102.   
  103.   from ${tableName}
  104.  
  105.  
  106.  
  107.   select
  108.   
  109.   from ${tableName}
  110.   
  111.    
  112.     and ${primaryId} in
  113.     
  114.                     ${r"#{" + "item" + r"}"}
  115.     
  116.    
  117.   
  118.  
  119.  
  120.  
  121.   select
  122.   
  123.   from ${tableName}
  124.  
  125.  
  126.  
  127.   select count(${primaryId})
  128.   from ${tableName}
  129.  
  130.  
  131.  
  132.   select
  133.   
  134.   from ${tableName}
  135.   limit ${r"#{" + "start,jdbcType=INTEGER" + r"}"},${r"#{" + "end,jdbcType=INTEGER" + r"}"}
  136.  

編寫dao.ftl數據訪問模板

 
 
 
 
  1. package ${daoPackageName};
  2. import com.example.generator.core.BaseMapper;
  3. import java.util.List;
  4. import ${entityPackageName}.${entityName};
  5. import ${dtoPackageName}.${dtoName};
  6. /**
  7. *
  8. * @ClassName: ${daoName}
  9. * @Description: 數據訪問接口
  10. * @author ${authorName}
  11. * @date ${currentTime}
  12. *
  13. */
  14. public interface ${daoName} extends BaseMapper<${entityName}>{
  15.  int countPage(${dtoName} ${dtoName?uncap_first});
  16.  List<${entityName}> selectPage(${dtoName} ${dtoName?uncap_first});
  17. }

編寫service.ftl服務接口模板

 
 
 
 
  1. package ${servicePackageName};
  2. import com.example.generator.core.BaseService;
  3. import com.example.generator.common.Pager;
  4. import ${voPackageName}.${voName};
  5. import ${dtoPackageName}.${dtoName};
  6. import ${entityPackageName}.${entityName};
  7. /**
  8.  *
  9.  * @ClassName: ${serviceName}
  10.  * @Description: ${entityName}業(yè)務訪問接口
  11.  * @author ${authorName}
  12.  * @date ${currentTime}
  13.  *
  14.  */
  15. public interface ${serviceName} extends BaseService<${entityName}> {
  16.  /**
  17.   * 分頁列表查詢
  18.   * @param request
  19.   */
  20.  Pager<${voName}> getPage(${dtoName} request);
  21. }

編寫serviceImpl.ftl服務實現類模板

 
 
 
 
  1. package ${serviceImplPackageName};
  2. import com.example.generator.common.Pager;
  3. import com.example.generator.core.BaseServiceImpl;
  4. import com.example.generator.test.service.TestEntityService;
  5. import org.springframework.beans.BeanUtils;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.util.CollectionUtils;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import ${daoPackageName}.${daoName};
  13. import ${entityPackageName}.${entityName};
  14. import ${dtoPackageName}.${dtoName};
  15. import ${voPackageName}.${voName};
  16. @Service
  17. public class ${serviceImplName} extends BaseServiceImpl<${daoName}, ${entityName}> implements ${serviceName} {
  18.  private static final Logger log = LoggerFactory.getLogger(${serviceImplName}.class);
  19.  /**
  20.   * 分頁列表查詢
  21.   * @param request
  22.   */
  23.  public Pager<${voName}> getPage(${dtoName} request) {
  24.   List<${voName}> resultList = new ArrayList();
  25.   int count = super.baseMapper.countPage(request);
  26.   List<${entityName}> dbList = count > 0 ? super.baseMapper.selectPage(request) : new ArrayList<>();
  27.   if(!CollectionUtils.isEmpty(dbList)){
  28.    dbList.forEach(source->{
  29.     ${voName} target = new ${voName}();
  30.     BeanUtils.copyProperties(source, target);
  31.     resultList.add(target);
  32.    });
  33.   }
  34.   return new Pager(request.getCurrPage(), request.getPageSize(), count, resultList);
  35.  }
  36. }

編寫controller.ftl控制層模板

 
 
 
 
  1. package ${controllerPackageName};
  2. import com.example.generator.common.IdRequest;
  3. import com.example.generator.common.Pager;
  4. import org.springframework.beans.BeanUtils;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import java.util.Objects;
  11. import ${servicePackageName}.${serviceName};
  12. import ${entityPackageName}.${entityName};
  13. import ${dtoPackageName}.${dtoName};
  14. import ${voPackageName}.${voName};
  15. /**
  16.  *
  17.  * @ClassName: ${controllerName}
  18.  * @Description: 外部訪問接口
  19.  * @author ${authorName}
  20.  * @date ${currentTime}
  21.  *
  22.  */
  23. @RestController
  24. @RequestMapping("/${entityName?uncap_first}")
  25. public class ${controllerName} {
  26.  @Autowired
  27.  private ${serviceName} ${serviceName?uncap_first};
  28.  /**
  29.   * 分頁列表查詢
  30.   * @param request
  31.   */
  32.  @PostMapping(value = "/getPage")
  33.  public Pager<${voName}> getPage(@RequestBody ${dtoName} request){
  34.   return ${serviceName?uncap_first}.getPage(request);
  35.  }
  36.  /**
  37.   * 查詢詳情
  38.   * @param request
  39.   */
  40.  @PostMapping(value = "/getDetail")
  41.  public ${voName} getDetail(@RequestBody IdRequest request){
  42.   ${entityName} source = ${serviceName?uncap_first}.selectById(request.getId());
  43.   if(Objects.nonNull(source)){
  44.    ${voName} result = new ${voName}();
  45.    BeanUtils.copyProperties(source, result);
  46.    return result;
  47.   }
  48.   return null;
  49.  }
  50.  /**
  51.   * 新增操作
  52.   * @param request
  53.   */
  54.  @PostMapping(value = "/save")
  55.  public void save(${dtoName} request){
  56.   ${entityName} entity = new ${entityName}();
  57.   BeanUtils.copyProperties(request, entity);
  58.   ${serviceName?uncap_first}.insert(entity);
  59.  }
  60.  /**
  61.   * 編輯操作
  62.   * @param request
  63.   */
  64.  @PostMapping(value = "/edit")
  65.  public void edit(${dtoName} request){
  66.   ${entityName} entity = new ${entityName}();
  67.   BeanUtils.copyProperties(request, entity);
  68.   ${serviceName?uncap_first}.updateById(entity);
  69.  }
  70.  /**
  71.   * 刪除操作
  72.   * @param request
  73.   */
  74.  @PostMapping(value = "/delete")
  75.  public void delete(IdRequest request){
  76.   ${serviceName?uncap_first}.deleteById(request.getId());
  77.  }
  78. }

編寫entity.ftl實體類模板

 
 
 
 
  1. package ${entityPackageName};
  2. import java.io.Serializable;
  3. import java.math.BigDecimal;
  4. import java.util.Date;
  5. /**
  6.  *
  7.  * @ClassName: ${entityName}
  8.  * @Description: ${tableDes!}實體類
  9.  * @author ${authorName}
  10.  * @date ${currentTime}
  11.  *
  12.  */
  13. public class ${entityName} implements Serializable {
  14.  private static final long serialVersionUID = 1L;
  15.  
  16.  <#--屬性遍歷-->
  17.  <#list columns as pro>
  18.  <#--<#if pro.proName != primaryId
  19.  && pro.proName != 'remarks'
  20.  && pro.proName != 'createBy'
  21.  && pro.proName != 'createDate'
  22.  && pro.proName != 'updateBy'
  23.  && pro.proName != 'updateDate'
  24.  && pro.proName != 'delFlag'
  25.  && pro.proName != 'currentUser'
  26.  && pro.proName != 'page'
  27.  && pro.proName != 'sqlMap'
  28.  && pro.proName != 'isNewRecord'
  29.  >-->
  30.  /**
  31.   * ${pro.proDes!}
  32.   */
  33.  private ${pro.proType} ${pro.proName};
  34.  
  35.  <#--屬性get||set方法-->
  36.  <#list columns as pro>
  37.  public ${pro.proType} get${pro.proName?cap_first}() {
  38.   return this.${pro.proName};
  39.  }
  40.  public ${entityName} set${pro.proName?cap_first}(${pro.proType} ${pro.proName}) {
  41.   this.${pro.proName} = ${pro.proName};
  42.   return this;
  43.  }
  44.  
  45. }

編寫dto.ftl實體類模板

 
 
 
 
  1. package ${dtoPackageName};
  2. import com.example.generator.core.BaseDTO;
  3. import java.io.Serializable;
  4. /**
  5.  * @ClassName: ${dtoName}
  6.  * @Description: 請求實體類
  7.  * @author ${authorName}
  8.  * @date ${currentTime}
  9.  *
  10.  */
  11. public class ${dtoName} extends BaseDTO {
  12. }

編寫vo.ftl視圖實體類模板

 
 
 
 
  1. package ${voPackageName};
  2. import java.io.Serializable;
  3. /**
  4.  * @ClassName: ${voName}
  5.  * @Description: 返回視圖實體類
  6.  * @author ${authorName}
  7.  * @date ${currentTime}
  8.  *
  9.  */
  10. public class ${voName} implements Serializable {
  11.  private static final long serialVersionUID = 1L;
  12. }

可能細心的網友已經看到了,在模板中我們用到了BaseMapper、BaseService、BaseServiceImpl等等服務類。

之所以有這三個類,是因為在模板中,我們有大量的相同的方法名包括邏輯也相似,除了所在實體類不一樣以外,其他都一樣,因此我們可以借助泛型類來將這些服務抽成公共的部分。

BaseMapper,主要負責將dao層的公共方法抽出來

 
 
 
 
  1. package com.example.generator.core;
  2. import org.apache.ibatis.annotations.Param;
  3. import java.io.Serializable;
  4. import java.util.List;
  5. import java.util.Map;
  6. /**
  7.  * @author pzblog
  8.  * @Description
  9.  * @since 2020-11-11
  10.  */
  11. public interface BaseMapper {
  12.     /**
  13.      * 批量插入
  14.      * @param list
  15.      * @return
  16.      */
  17.     int insertList(@Param("list") List list);
  18.     /**
  19.      * 按需插入一條記錄
  20.      * @param entity
  21.      * @return
  22.      */
  23.     int insertPrimaryKeySelective(T entity);
  24.     /**
  25.      * 按需修改一條記錄(通過主鍵ID)
  26.      * @return
  27.      */
  28.     int updatePrimaryKeySelective(T entity);
  29.     /**
  30.      * 批量按需修改記錄(通過主鍵ID)
  31.      * @param list
  32.      * @return
  33.      */
  34.     int updateBatchByIds(@Param("list") List list);
  35.     /**
  36.      * 根據ID刪除
  37.      * @param id 主鍵ID
  38.      * @return
  39.      */
  40.     int deleteByPrimaryKey(Serializable id);
  41.     /**
  42.      * 根據ID查詢
  43.      * @param id 主鍵ID
  44.      * @return
  45.      */
  46.     T selectByPrimaryKey(Serializable id);
  47.     /**
  48.      * 按需查詢
  49.      * @param entity
  50.      * @return
  51.      */
  52.     List selectByPrimaryKeySelective(T entity);
  53.     /**
  54.      * 批量查詢
  55.      * @param ids 主鍵ID集合
  56.      * @return
  57.      */
  58.     List selectByIds(@Param("ids") List ids);
  59.     /**
  60.      * 查詢(根據 columnMap 條件)
  61.      * @param columnMap 表字段 map 對象
  62.      * @return
  63.      */
  64.     List selectByMap(Map columnMap);
  65. }

BaseService,主要負責將service層的公共方法抽出來

 
 
 
 
  1. package com.example.generator.core;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. import java.util.Map;
  5. /**
  6.  * @author pzblog
  7.  * @Description 服務類
  8.  * @since 2020-11-11
  9.  */
  10. public interface BaseService {
  11.     /**
  12.      * 新增
  13.      * @param entity
  14.      * @return boolean
  15.      */
  16.     boolean insert(T entity);
  17.     /**
  18.      * 批量新增
  19.      * @param list
  20.      * @return boolean
  21.      */
  22.     boolean insertList(List list);
  23.     /**
  24.      * 通過ID修改記錄(如果想全部更新,只需保證字段都不為NULL)
  25.      * @param entity
  26.      * @return boolean
  27.      */
  28.     boolean updateById(T entity);
  29.     /**
  30.      * 通過ID批量修改記錄(如果想全部更新,只需保證字段都不為NULL)
  31.      * @param list
  32.      * @return boolean
  33.      */
  34.     boolean updateBatchByIds(List list);
  35.     /**
  36.      * 根據ID刪除
  37.      * @param id 主鍵ID
  38.      * @return boolean
  39.      */
  40.     boolean deleteById(Serializable id);
  41.     /**
  42.      * 根據ID查詢
  43.      * @param id 主鍵ID
  44.      * @return
  45.      */
  46.     T selectById(Serializable id);
  47.     /**
  48.      * 按需查詢
  49.      * @param entity
  50.      * @return
  51.      */
  52.     List selectByPrimaryKeySelective(T entity);
  53.     /**
  54.      * 批量查詢
  55.      * @param ids
  56.      * @return
  57.      */
  58.     List selectByIds(List ids);
  59.     /**
  60.      * 根據條件查詢
  61.      * @param columnMap
  62.      * @return
  63.      */
  64.     List selectByMap(Map columnMap);
  65. }

BaseServiceImpl,service層的公共方法具體實現類

 
 
 
 
  1. package com.example.generator.core;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.transaction.annotation.Transactional;
  4. import java.io.Serializable;
  5. import java.util.List;
  6. import java.util.Map;
  7. /**
  8.  * @author pzblog
  9.  * @Description 實現類( 泛型說明:M 是 mapper 對象,T 是實體)
  10.  * @since 2020-11-11
  11.  */
  12. public abstract class BaseServiceImpl, T> implements BaseService{
  13.     @Autowired
  14.     protected M baseMapper;
  15.     /**
  16.      * 新增
  17.      * @param entity
  18.      * @return boolean
  19.      */
  20.     @Override
  21.     @Transactional(rollbackFor = {Exception.class})
  22.     public boolean insert(T entity){  分享文章:你還在手寫crud嗎,看完這篇文章,絕對賺了
    本文網址:http://www.5511xx.com/article/djocoep.html