一、引言
在項(xiàng)目開發(fā)中,我們有碰到大量的簡單、重復(fù)的增刪改查需求,通過閱讀若依框架https://github.com/yangzongzhuan/RuoYi?的代碼生成器實(shí)現(xiàn),結(jié)合我項(xiàng)目所用的技術(shù)棧,開發(fā)出本項(xiàng)目的代碼生成器。
二、Velocity?簡單介紹
1、Velocity是一個(gè)基于Java的模板引擎,我們可以往Context容器中填值,在vm文件中使用模板語言(Velocity Template Language)獲取變量的值,生成一套通用的模板代碼。
2、引入依賴:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
3、語法示例:
獲取Context中的ClassName值:${ClassName}
判斷:#if($table.crud || $table.sub)? ? ?
遍歷:#foreach ($column in $columns)
結(jié)束:#end
/**
* ${functionName}對象 ${tableName}
*
* @author ${author}
* @date ${datetime}
*/
#if($table.crud || $table.sub)
#set($Entity="BaseEntity")
#elseif($table.tree)
#set($Entity="TreeEntity")
#end
@Data
public class ${ClassName} extends BasicEntity
{
private static final long serialVersionUID = 1L;
#foreach ($column in $columns)
#if(!$table.isSuperColumn($column.javaField))
/** $column.columnComment */
#if($column.list)
#set($parentheseIndex=$column.columnComment.indexOf("("))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if($parentheseIndex != -1)
@Excel(name = "${comment}", readConverterExp = "$column.readConverterExp()")
#elseif($column.javaType == 'Date')
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "${comment}", width = 30, dateFormat = "yyyy-MM-dd")
#else
@Excel(name = "${comment}")
#end
#end
private $column.javaType $column.javaField;
#end
#end
#if($table.sub)
/** $table.subTable.functionName信息 */
private List<${subClassName}> ${subclassName}List;
#end
}
三、若依代碼生成器核心源碼閱讀
前置:根據(jù)業(yè)務(wù)代碼和模板語言編寫代碼模板
1、獲取數(shù)據(jù)庫表列表,查詢?information_schema.tables 表
select table_name, table_comment, create_time, update_time
from information_schema.tables
where table_schema = (select database())
2、初始化表結(jié)構(gòu)信息,填充代碼生成器基本信息,插入到 gen_table表
public static void initTable(GenTable genTable, String operName)
{
genTable.setClassName(convertClassName(genTable.getTableName()));
genTable.setPackageName(GenConfig.getPackageName());
genTable.setModuleName(getModuleName(GenConfig.getPackageName()));
genTable.setBusinessName(getBusinessName(genTable.getTableName()));
genTable.setFunctionName(replaceText(genTable.getTableComment()));
genTable.setFunctionAuthor(GenConfig.getAuthor());
genTable.setCreateBy(operName);
}
3、初始化表的列信息:查詢 information_schema.`COLUMNS`表,插入到 gen_table_column表
select table_name, column_name, column_type, data_type, column_comment, column_key
from information_schema.`COLUMNS`
where table_schema = 'smart_ca' and table_name = '表名'
4、初始化vm,加載模板
public static void initVelocity()
{
Properties p = new Properties();
try {
// 加載classpath目錄下的vm文件
p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// 定義字符集
p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8);
// 初始化Velocity引擎,指定配置Properties
Velocity.init(p);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
5、給容器Context中設(shè)置模板變量(重要),例:
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("tplCategory", genTable.getTplCategory());
velocityContext.put("tableName", genTable.getTableName());
velocityContext.put("ClassName", genTable.getClassName());
velocityContext.put("moduleName", genTable.getModuleName());
6、設(shè)置模板
List<String> templates = new ArrayList<String>();
templates.add("vm/java/domain.java.vm");
templates.add("vm/java/mapper.java.vm");
templates.add("vm/java/service.java.vm");
templates.add("vm/java/serviceImpl.java.vm");
templates.add("vm/java/controller.java.vm");
7、渲染模板,生成至指定位置
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
String path = getGenPath(table, template);
FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
四、結(jié)合項(xiàng)目業(yè)務(wù)開發(fā)代碼生成器
1、梳理項(xiàng)目通用代碼(重要)
和團(tuán)隊(duì)成員一同梳理出通用的代碼,我們是要一鍵生成前后端代碼,直接實(shí)現(xiàn)增刪改查。模板代碼必須是經(jīng)過前后端同學(xué)一起驗(yàn)證,避免反復(fù)修改。
2、結(jié)合自己的業(yè)務(wù),定義所有需要的變量,并且使用velocity模板語法,使用變量替換代碼。
3、編寫操作后臺(tái),將模板中需要用到的變量,存儲(chǔ)到gen_table,gen_table_column表,以便整個(gè)流程使用。
4、開發(fā)者點(diǎn)擊代碼生成時(shí),查詢gen_table, gen_table_column表中的數(shù)據(jù),設(shè)置模板變量到容器Context中,這邊要注意把之前自定義的變量全部 put
5、設(shè)置代碼生成路徑,我們的代碼默認(rèn)生成在項(xiàng)目根路徑的 generator目錄。文章來源:http://www.zghlxwxcb.cn/news/detail-613682.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-613682.html
到了這里,關(guān)于基于Velocity開發(fā)代碼生成器的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!