业务代码存在大量的增删改查功能,只是针对不同的表数据而已。这时候就如果能生成固定的模板代码,那么将大大的解放生产力。本文我们将使用Freemarker模板来生成业务模板代码。
FreeMarker
FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。其用法原理类似String的replace方法,或MessageFormat的format方法,都是在一定的代码中改变(替换)某些内容。不过FreeMarker更加强大,模板来源可以是外部文件或字符串格式,替换的数据格式多样,而且支持逻辑判断,如此替换的内容将更加灵活。
上代码
准备模板
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} 对象
*/
void save(${classNameUpper} ${classNameLower});
/**
* 删除
*
* @param id id
*/
void delete(Long id);
/**
* 修改
*
* @param ${classNameLower} 对象
*/
void update(${classNameUpper} ${classNameLower});
/**
* 分页
*
* @param page 分页信息
* @return 结果
*/
Page<${classNameUpper}> page(BasePage<${classNameUpper}> page);
/**
* 通过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,其余相关包在父级
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
编码替换
原理很简单,在此不过多赘述,直接上代码
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("创建文件夹失败");
}
}
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"),
/**
* 实体
*/
ENTITY("entity.java.ftl", "entity", "%s.java"),
/**
* 数据库mapper
*/
MAPPER("mapper.java.ftl", "dao", "%sDao.java"),
/**
* service接口
*/
SERVICE("service.java.ftl", "service", "I%sService.java"),
/**
* service实现
*/
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;
}
其它
这里只是简单的创建了模板,还可以扩展到自动从数据库拉取字段创建实体等。