1. 程式人生 > >Beetlsql自定義生成entity,mapper,md程式碼

Beetlsql自定義生成entity,mapper,md程式碼

三個模板檔案 

mapper.btl

package ${package};
import org.beetl.sql.core.annotatoin.*;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.mapper.BaseMapper;
${imports}

public interface ${className} extends BaseMapper<${entityClass
}> { // }

 

md.btl

<%

var tableAlias = alias==null?"":(alias+".");//如果沒有設定alias,則預設為t
%>
sample
===
* 註釋###

    select ${PS}use("cols")${PE} from ${tableName} ${alias} where  ${PS}use("condition")${PE}

cols
===
    <%
    print("\t");
    for(col in cols){
     var colName
=tableAlias+col+(colLP.last?"":","); print(colName); }%> updateSample === <% print("\t"); for(col in cols){ var colName=tableAlias+col; var attr = @nc.getPropertyName(col); print(colName+"="+PS+attr+PE); if(!colLP.last){ print(
","); } }%> condition === 1 = 1 <% for(col in cols){ var colName=tableAlias+col; var attr = @nc.getPropertyName(col); %> ${SS}if(!isEmpty(${attr})){${SE} and ${colName}=${PS+attr+PE} ${SS}}${SE} <%}%>
View Code

 

pojo.btl 

因為我想用lombok 所以使用@Setter ..註解

package ${package};
import lombok.*;
${imports}
${implSerializable?"import java.io.Serializable;"}

@Table(name="${catalog}.${table}")
@Setter
@Getter
@NoArgsConstructor
public class ${className} ${!isEmpty(ext)?"extends "+ext} ${implSerializable?"implements Serializable"} {
    
    <%for(attr in attrs){
            if(!isEmpty(attr.comment)){%>
    /*
    *${attr.comment}
    */
    <%        }%>
    private ${attr.type} ${attr.name} ;
    <%}%>

}

 

BeetlGenCode.java

package com.github.tungss.auth;

import org.beetl.sql.core.*;
import org.beetl.sql.core.db.*;
import org.beetl.sql.core.kit.*;
import org.beetl.sql.ext.gen.*;

import java.io.*;
import java.util.Set;

/**
 * 生成dao程式碼.
 */

public class BeetlGenCode {
    // ========資料庫配置=========
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql:///auth?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC";
    private static String userName = "root";
    private static String password = "123456";
    // ========模板的路徑, 示例是spring boot的[src/main/resources/beetlsqlTemplate 資料夾]=========
    private static String templatePath = "/beetlsqlTemplate";
    // ========md生成路徑 要提前建立=========
    private static String mdPath = "/sql";
    // ========生成實體類所在的包=========
    private static String pojoPkg = "com.test.entity";
    // ========生成mapper類所在的包=========
    private static String mapperPkg = "com.test.dao";

    /**
     * 入口
     */
    public static void main(String[] args) throws Exception {
        genAll();
    }

    public static void genAll() throws Exception {
        //準備工作
        ConnectionSource source = ConnectionSourceHelper.getSimple(driver, url, userName, password);
        DBStyle mysql = new MySqlStyle();
        SQLLoader loader = new ClasspathLoader(mdPath);
        UnderlinedNameConversion nc = new UnderlinedNameConversion();
        SQLManager sqlManager = new SQLManager(mysql, loader, source, nc, null);

        GenConfig config = new GenConfig();
        config.setDisplay(false);
        config.setPreferBigDecimal(true);

        System.out.println("======生成程式碼======");
        Set<String> tables = sqlManager.getMetaDataManager().allTable();
        for (String table : tables) {
            System.out.printf("%-20s %s\n",table , "生成完畢");
            //預設生成實體類的實現
            sqlManager.genPojoCode(table, pojoPkg, config);
            //自定義實現
            genMd(sqlManager, config, table);
            //自定義實現
            genMapper(sqlManager, config, table);
        }
        System.out.println("=====生成完畢=====");
    }

    /**
     * 生成md檔案
     */
    public static void genMd(SQLManager sqlManager, GenConfig config, String table) throws IOException {
        String fileName = StringKit.toLowerCaseFirstOne(sqlManager.getNc().getClassName(table));
        if (config.getIgnorePrefix() != null && !config.getIgnorePrefix().trim().equals("")) {
            fileName = fileName.replaceFirst(StringKit.toLowerCaseFirstOne(config.getIgnorePrefix()), "");
            fileName = StringKit.toLowerCaseFirstOne(fileName);
        }
        String target = GenKit.getJavaResourcePath() + "/" + mdPath + "/" + fileName + ".md";
        TableDesc desc = sqlManager.getMetaDataManager().getTable(table);
        FileWriter writer = new FileWriter(new File(target));
        MDCodeGen mdCodeGen = new MDCodeGen();
        mdCodeGen.setMapperTemplate(config.getTemplate(templatePath + "/md.btl"));
        mdCodeGen.genCode(sqlManager.getBeetl(), desc, sqlManager.getNc(), null, writer);
        writer.close();
    }

    /**
     * 生成mapper
     */
    public static void genMapper(SQLManager sqlManager, GenConfig config, String table) {
        MapperCodeGen mapperCodeGen = new MapperCodeGen(mapperPkg);
        mapperCodeGen.setMapperTemplate(config.getTemplate(templatePath + "/mapper.btl"));
        mapperCodeGen.genCode(pojoPkg, sqlManager.getNc().getClassName(table), sqlManager.getMetaDataManager().getTable(table), null, false);
    }
}