業(yè)務(wù)代碼存在大量的增刪改查功能疼电,只是針對(duì)不同的表數(shù)據(jù)而已分衫。這時(shí)候就如果能生成固定的模板代碼,那么將大大的解放生產(chǎn)力肩民。本文我們將使用Freemarker模板來(lái)生成業(yè)務(wù)模板代碼唠亚。
FreeMarker
FreeMarker是一款模板引擎: 即一種基于模板和要改變的數(shù)據(jù), 并用來(lái)生成輸出文本(HTML網(wǎng)頁(yè)持痰、電子郵件灶搜、配置文件、源代碼等)的通用工具工窍。其用法原理類似String的replace方法割卖,或MessageFormat的format方法,都是在一定的代碼中改變(替換)某些內(nèi)容患雏。不過(guò)FreeMarker更加強(qiáng)大鹏溯,模板來(lái)源可以是外部文件或字符串格式,替換的數(shù)據(jù)格式多樣淹仑,而且支持邏輯判斷丙挽,如此替換的內(nèi)容將更加靈活。
上代碼
準(zhǔn)備模板
controller.java.ftl
package ${basePath}.${module}.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${basePath}.common.mybatis.page.BasePage;
import ${basePath}.common.mybatis.page.PageResult;
import ${basePath}.${module}.entity.${classNameUpper};
import ${basePath}.${module}.service.I${classNameUpper}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* ${desc}控制器
*
* @author lieber
*/
@RestController
@RequestMapping("${router}")
public class ${classNameUpper}Controller {
private final I${classNameUpper}Service ${classNameLower}Service;
@Autowired
public ${classNameUpper}Controller(I${classNameUpper}Service ${classNameLower}Service) {
this.${classNameLower}Service = ${classNameLower}Service;
}
@PostMapping
public ${classNameUpper} add(@Validated ${classNameUpper} ${classNameLower}) {
this.${classNameLower}Service.save(${classNameLower});
return ${classNameLower};
}
@DeleteMapping
public void del(Long id) {
this.${classNameLower}Service.delete(id);
}
@PutMapping
public ${classNameUpper} edit(@Validated ${classNameUpper} ${classNameLower}) {
this.${classNameLower}Service.update(${classNameLower});
return ${classNameLower};
}
@GetMapping
public PageResult<${classNameUpper}> page(BasePage<${classNameUpper}> page) {
Page<${classNameUpper}> pageRes = this.${classNameLower}Service.page(page);
return new PageResult<>(pageRes);
}
@GetMapping("{id}")
public ${classNameUpper} detail(@PathVariable Long id) {
return this.${classNameLower}Service.getById(id);
}
}
entity.java.ftl
package ${basePath}.${module}.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import ${basePath}.common.mybatis.model.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.io.Serializable;
/**
* ${desc}
*
* @author lieber
*/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
@TableName("t_skp_${tableName}")
public class ${classNameUpper} extends BaseEntity implements Serializable {
}
mapper.java.ftl
package ${basePath}.${module}.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import ${basePath}.${module}.entity.${classNameUpper};
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
* @author lieber
*/
@Repository
@Mapper
public interface ${classNameUpper}Dao extends BaseMapper<${classNameUpper}> {
}
service.java.ftl
package ${basePath}.${module}.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${basePath}.common.mybatis.page.BasePage;
import ${basePath}.${module}.entity.${classNameUpper};
/**
* @author lieber
*/
public interface I${classNameUpper}Service {
/**
* 保存
*
* @param ${classNameLower} 對(duì)象
*/
void save(${classNameUpper} ${classNameLower});
/**
* 刪除
*
* @param id id
*/
void delete(Long id);
/**
* 修改
*
* @param ${classNameLower} 對(duì)象
*/
void update(${classNameUpper} ${classNameLower});
/**
* 分頁(yè)
*
* @param page 分頁(yè)信息
* @return 結(jié)果
*/
Page<${classNameUpper}> page(BasePage<${classNameUpper}> page);
/**
* 通過(guò)id獲取
*
* @param id id
* @return 詳情
*/
${classNameUpper} getById(Long id);
}
serviceImpl.java.ftl
package ${basePath}.${module}.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${basePath}.common.mybatis.page.BasePage;
import ${basePath}.${module}.dao.${classNameUpper}Dao;
import ${basePath}.${module}.entity.${classNameUpper};
import ${basePath}.${module}.service.I${classNameUpper}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
* @author lieber
*/
@Service
public class ${classNameUpper}ServiceImpl implements I${classNameUpper}Service {
private final ${classNameUpper}Dao ${classNameLower}Dao;
@Autowired
public ${classNameUpper}ServiceImpl(${classNameUpper}Dao ${classNameLower}Dao) {
this.${classNameLower}Dao = ${classNameLower}Dao;
}
@Override
public void save(${classNameUpper} ${classNameLower}) {
${classNameLower}.set(false);
this.${classNameLower}Dao.insert(${classNameLower});
}
@Override
public void delete(Long id) {
this.${classNameLower}Dao.deleteById(id);
}
@Override
public void update(${classNameUpper} ${classNameLower}) {
${classNameLower}.set(true);
this.${classNameLower}Dao.updateById(${classNameLower});
}
@Override
public Page<${classNameUpper}> page(BasePage<${classNameUpper}> page) {
QueryWrapper<${classNameUpper}> queryWrapper = new QueryWrapper<>();
return this.${classNameLower}Dao.selectPage(page.toPage(), queryWrapper);
}
@Override
public ${classNameUpper} getById(Long id) {
if (Objects.isNull(id) || id < 0) {
return null;
}
return this.${classNameLower}Dao.selectById(id);
}
}
引入freemarker處理包
此處僅引入freemarker匀借,其余相關(guān)包在父級(jí)
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
編碼替換
原理很簡(jiǎn)單颜阐,在此不過(guò)多贅述,直接上代碼
CodeGenerator
package com.yugioh.code;
import com.sun.javafx.PlatformUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.*;
/**
* @author lieber
*/
public class CodeGenerator {
public static void main(String[] args) throws IOException, TemplateException {
CodeModel codeModel = new CodeModel();
codeModel.setRouter("test");
codeModel.setClassNameLower("test");
codeModel.setClassNameUpper("Test");
codeModel.setModule("ready");
codeModel.setTableName("test");
codeModel.setDesc("test");
gen(codeModel);
}
public static void gen(CodeModel codeModel) throws IOException, TemplateException {
for (Type type : Type.values()) {
genFile(codeModel, type);
}
}
private static void genFile(CodeModel codeModel, Type type) throws IOException, TemplateException {
FileOutputStream stream = null;
OutputStreamWriter outputStreamWriter = null;
try {
Map<String, Object> rootMap = getGenMap(codeModel);
String projectPath = System.getProperty("user.dir");
Configuration configuration = new Configuration(Configuration.getVersion());
String templatePath = projectPath + "/code-gen/src/main/resources/templates/";
configuration.setDirectoryForTemplateLoading(new File(parsePath(templatePath)));
Template template = configuration.getTemplate(type.getPath());
String savePath = projectPath + "/" + codeModel.getModule() + "/src/main/java/" + codeModel.getBasePath().replaceAll("\\.", "/") + "/" + codeModel.getModule() + "/" + type.getPackageName();
File dir = new File(parsePath(savePath));
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw new IOException("創(chuàng)建文件夾失敗");
}
}
stream = new FileOutputStream(parsePath(savePath + "/" + String.format(type.getClassName(), codeModel.getClassNameUpper())));
outputStreamWriter = new OutputStreamWriter(stream);
template.process(rootMap, outputStreamWriter);
outputStreamWriter.flush();
outputStreamWriter.close();
stream.close();
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (stream != null) {
stream.close();
}
}
}
private static Map<String, Object> getGenMap(CodeModel codeModel) {
Map<String, Object> genMap = new HashMap<>(16);
genMap.put("basePath", codeModel.getBasePath());
genMap.put("router", codeModel.getRouter());
genMap.put("desc", codeModel.getDesc());
genMap.put("classNameUpper", codeModel.getClassNameUpper());
genMap.put("classNameLower", codeModel.getClassNameLower());
genMap.put("module", codeModel.getModule());
genMap.put("tableName", codeModel.getTableName());
return genMap;
}
private static String parsePath(String path) {
if (PlatformUtil.isWindows()) {
return path.replaceAll("/+|\\\\+", "\\\\");
} else {
return path.replaceAll("/+|\\\\+", "/");
}
}
public enum Type {
/**
* 控制器
*/
CONTROLLER("controller.java.ftl", "controller", "%sController.java"),
/**
* 實(shí)體
*/
ENTITY("entity.java.ftl", "entity", "%s.java"),
/**
* 數(shù)據(jù)庫(kù)mapper
*/
MAPPER("mapper.java.ftl", "dao", "%sDao.java"),
/**
* service接口
*/
SERVICE("service.java.ftl", "service", "I%sService.java"),
/**
* service實(shí)現(xiàn)
*/
SERVICE_IMPL("serviceImpl.java.ftl", "service/impl", "%sServiceImpl.java");
private String path;
private String packageName;
private String className;
Type(String path, String packageName, String className) {
this.path = path;
this.packageName = packageName;
this.className = className;
}
public String getPath() {
return path;
}
public String getPackageName() {
return packageName;
}
public String getClassName() {
return className;
}
}
}
CodeModel
package com.yugioh.code;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author lieber
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CodeModel {
private String basePath = "com.yugioh";
private String router;
private String desc;
private String classNameUpper;
private String classNameLower;
private String module;
private String tableName;
}
其它
這里只是簡(jiǎn)單的創(chuàng)建了模板吓肋,還可以擴(kuò)展到自動(dòng)從數(shù)據(jù)庫(kù)拉取字段創(chuàng)建實(shí)體等凳怨。