SpringBoot代碼生成器,從此不用手?jǐn)]代碼

image

前言

通常在開始開發(fā)項目的時候对嚼,首先會建立好數(shù)據(jù)庫相關(guān)表夹抗,然后根據(jù)表結(jié)構(gòu)生成 Controller、Service纵竖、DAO漠烧、Model以及一些前端頁面。

如果開發(fā)前沒有強(qiáng)制的約束靡砌,而每個程序員都有自己的編碼習(xí)慣已脓,最終會導(dǎo)致一個項目呈現(xiàn)出多種編碼風(fēng)格。再有就是一些CRUD的列表功能通殃,基本是沒啥挑戰(zhàn)性的度液,純粹苦力活,浪費(fèi)時間邓了。

所以恨诱,根據(jù)公司現(xiàn)有框架媳瞪,開發(fā)一款統(tǒng)一風(fēng)格的代碼生成器還是很有必要的骗炉。

技術(shù)選型

開發(fā)框架:SpringBoot+JPA,考慮到會生成各種前后端代碼文件蛇受,這里我們選用freemarker模板引擎來制作相應(yīng)的模板句葵。

實(shí)現(xiàn)思路

獲取表結(jié)構(gòu)信息

首先我們定義一個實(shí)體類,為了使用方便兢仰,把表和字段信息放到了一個類中:

/**
 * 表以及相關(guān)字段信息
 */
@Data
public class AppGen extends PageBean implements Serializable {

    /**
     * 表名
     */
    private String tableName;
    /**
     * 實(shí)體類名
     */
    private String entityName;
    /**
     * 實(shí)體類名 首字母小寫
     */
    private String lowerEntityName;
    /**
     * 表備注
     */
    private String tableComment;
    /**
     * 表前綴
     */
    private String prefix;
    /**
     * 功能描述
     */
    private String function;

    /**
     * 列名
     */
    private String columnName;
    /**
     * 實(shí)體列名
     */
    private String entityColumnName;
    /**
     * 列描述
     */
    private String columnComment;

    /**
     * 類型
     */
    private String dataType;

    /**
     * 自增
     */
    private Object columnExtra;
    /**
     * 長度
     */
    private Object columnLength;

    private List<AppGen> list;

}

獲取表列表:

@Override
@Transactional(readOnly = true)
public Result list(AppGen gen){
    String countSql = "SELECT COUNT(*) FROM information_schema.tables ";
    countSql +="WHERE table_schema='tools'";
    Long totalCount = dynamicQuery.nativeQueryCount(countSql);
    PageBean<AppGen> data = new PageBean<>();
    if(totalCount>0){
        String nativeSql = "SELECT table_name as tableName,table_comment as tableComment ";
        nativeSql+="FROM information_schema.tables WHERE table_schema='tools'";
        Pageable pageable = PageRequest.of(gen.getPageNo(),gen.getPageSize());
        List<AppGen> list = dynamicQuery.nativeQueryPagingListModel(AppGen.class,pageable, nativeSql);
        data = new PageBean<>(list, totalCount);
    }
    return Result.ok(data);
}
image

制作模板

模板太多了乍丈,這里只以Controller模板為例,貼一下實(shí)現(xiàn)代碼把将,更多模板見源碼:

package com.tools.module.${prefix}.web;

import com.tools.common.config.AbstractController;
import com.tools.common.model.Result;
import com.tools.module.${prefix}.entity.${entityName};
import com.tools.module.${prefix}.service.${entityName}Service;
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;


@RestController
@RequestMapping("/${prefix}/${function}")
public class ${entityName}Controller extends AbstractController {

    @Autowired
    private ${entityName}Service ${function}Service;

    /**
     * 列表
     */
    @PostMapping("/list")
    public Result list(${entityName} ${function}){
        return ${function}Service.list(${function});
    }
    /**
     * 查詢
     */
    @PostMapping("/get")
    public Result get(Long id){
        return ${function}Service.get(id);
    }
    /**
     * 保存
     */
    @PostMapping("/save")
    public Result save(@RequestBody ${entityName} ${function}){
        return ${function}Service.save(${function});
    }

    /**
     * 刪除
     */
    @PostMapping("/delete")
    public Result delete(Long id){
        return ${function}Service.delete(id);
    }
}

說白了其實(shí)就是傳遞參數(shù)轻专,把一些可變的代碼片段使用${name}形式編寫。

代碼生成

有點(diǎn)長察蹲,慢慢看请垛,其實(shí)就是渲染各種前后端模板:

/**
 * 生成代碼
 * @param gen
 * @return
 * @throws IOException
 * @throws TemplateException
 */
@PostMapping("/create")
public Result create(@RequestBody AppGen gen) throws IOException, TemplateException {
    /**
     * 獲取表字段以及注釋
     */
    List<AppGen> list = genService.getByTable(gen);
    String name = gen.getTableName();
    String[] table =  StringUtils.split(name,"_");
    gen.setPrefix(table[0]);
    gen.setFunction(table[1]);
    gen.setEntityName(GenUtils.allInitialCapital(gen.getTableName()));
    list.stream().forEach(column-> {
       column.setEntityColumnName(GenUtils.secInitialCapital(column.getColumnName()));
    });
    gen.setList(list);
    String baseFile = filePath+ SystemConstant.SF_FILE_SEPARATOR+"com"+
            SystemConstant.SF_FILE_SEPARATOR+ "tools"+
            SystemConstant.SF_FILE_SEPARATOR+ "module"+
            SystemConstant.SF_FILE_SEPARATOR+ gen.getPrefix()+SystemConstant.SF_FILE_SEPARATOR;
    /**
     * 后端代碼
     */
    File entityFile = FileUtil.touch(baseFile+"entity"+
            SystemConstant.SF_FILE_SEPARATOR+gen.getEntityName()+".java");
    File repositoryFile = FileUtil.touch(baseFile+"repository"+
            SystemConstant.SF_FILE_SEPARATOR+gen.getEntityName()+"Repository.java");
    File serviceFile = FileUtil.touch(baseFile+"service"+
            SystemConstant.SF_FILE_SEPARATOR+gen.getEntityName()+"Service.java");
    File serviceImplFile = FileUtil.touch(baseFile+"service"+
            SystemConstant.SF_FILE_SEPARATOR+"impl"+SystemConstant.SF_FILE_SEPARATOR+
            gen.getEntityName()+"ServiceImpl.java");
    File controllerFile = FileUtil.touch(baseFile+"web"+
            SystemConstant.SF_FILE_SEPARATOR + gen.getEntityName() + "Controller.java");
    /**
     * 前端代碼
     */
    String htmlPath =  filePath+
            SystemConstant.SF_FILE_SEPARATOR + "templates"+
            SystemConstant.SF_FILE_SEPARATOR + gen.getPrefix()+
            SystemConstant.SF_FILE_SEPARATOR + gen.getFunction()+SystemConstant.SF_FILE_SEPARATOR;
    File listFile = FileUtil.touch(htmlPath + "list.html");
    File formFile = FileUtil.touch(htmlPath + "form.html");
    /**
     * 生成靜態(tài)頁面
     */
    Template template = configuration.getTemplate("html/list.ftl");
    String text = FreeMarkerTemplateUtils.processTemplateIntoString(
            template, gen);
    FileUtil.writeString(text,listFile,"UTF-8");
    template = configuration.getTemplate("html/form.ftl");
    text = FreeMarkerTemplateUtils.processTemplateIntoString(
            template, gen);
    FileUtil.writeString(text,formFile,"UTF-8");
    /**
     * 生成后端代碼 repository
     */
    template = configuration.getTemplate("java/repository.ftl");
    text = FreeMarkerTemplateUtils.processTemplateIntoString(
            template, gen);
    FileUtil.writeString(text,repositoryFile,"UTF-8");
    /**
     * 生成后端代碼 entity
     */
    template = configuration.getTemplate("java/entity.ftl");
    text = FreeMarkerTemplateUtils.processTemplateIntoString(
            template, gen);
    FileUtil.writeString(text,entityFile,"UTF-8");
    /**
     * 生成后端代碼 service
     */
    template = configuration.getTemplate("java/service.ftl");
    text = FreeMarkerTemplateUtils.processTemplateIntoString(
            template, gen);
    FileUtil.writeString(text,serviceFile,"UTF-8");
    /**
     * 生成后端代碼 service 實(shí)現(xiàn)
     */
    template = configuration.getTemplate("java/serviceImpl.ftl");
    text = FreeMarkerTemplateUtils.processTemplateIntoString(
            template, gen);
    FileUtil.writeString(text,serviceImplFile,"UTF-8");
    /**
     * 生成后端代碼 controller 實(shí)現(xiàn)
     */
    template = configuration.getTemplate("java/controller.ftl");
    text = FreeMarkerTemplateUtils.processTemplateIntoString(
            template, gen);
    FileUtil.writeString(text,controllerFile,"UTF-8");
    return Result.ok();
}

生成邏輯還是很傻瓜的,后期會慢慢優(yōu)化洽议,比如根據(jù)字段類型生成不同的表單形式宗收,可以自定義字段是否顯示等的。

小結(jié)

總的來說亚兄,還是比較容易上手的混稽,相對于一些簡單的列表功能分分鐘擼出效果,開發(fā)一分鐘,喝茶一整天匈勋。當(dāng)然對于一些復(fù)雜的效果礼旅,還是自己一一去實(shí)現(xiàn)。

源碼

https://gitee.com/52itstyle/SPTools

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末洽洁,一起剝皮案震驚了整個濱河市各淀,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌诡挂,老刑警劉巖碎浇,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異璃俗,居然都是意外死亡奴璃,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門城豁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來苟穆,“玉大人,你說我怎么就攤上這事唱星■茫” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵间聊,是天一觀的道長攒盈。 經(jīng)常有香客問我,道長哎榴,這世上最難降的妖魔是什么型豁? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮尚蝌,結(jié)果婚禮上迎变,老公的妹妹穿的比我還像新娘。我一直安慰自己飘言,他們只是感情好衣形,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著姿鸿,像睡著了一般谆吴。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上般妙,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天纪铺,我揣著相機(jī)與錄音,去河邊找鬼碟渺。 笑死鲜锚,一個胖子當(dāng)著我的面吹牛突诬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播芜繁,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼旺隙,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了骏令?” 一聲冷哼從身側(cè)響起蔬捷,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎榔袋,沒想到半個月后周拐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡凰兑,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年妥粟,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片吏够。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡勾给,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出锅知,到底是詐尸還是另有隱情播急,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布售睹,位于F島的核電站桩警,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏侣姆。R本人自食惡果不足惜生真,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一沉噩、第九天 我趴在偏房一處隱蔽的房頂上張望捺宗。 院中可真熱鬧,春花似錦川蒙、人聲如沸蚜厉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽昼牛。三九已至,卻和暖如春康聂,著一層夾襖步出監(jiān)牢的瞬間贰健,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工恬汁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留伶椿,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像脊另,于是被迫代替她去往敵國和親导狡。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355