大家好,欢迎来到IT知识分享网。
4.2 编码
4.2.1 常量类
package freemarker.constant; public class TemplateConstant { //实体类模板 public static final String entityTemplate = "templates/Entity.ftl"; //Mapper模板 public static final String mapperTemplate = "templates/Mapper.ftl"; //Mapper映射文件模版 public static final String mapperXmlTemplate = "templates/MapperXml.ftl"; //service模版 public static final String serviceTemplate = "templates/Service.ftl"; //service实现类模版 public static final String serviceImplTemplate = "templates/ServiceImpl.ftl"; //controller模版 public static final String controllerTemplate = "templates/Controller.ftl"; //vo模版 public static final String entityVoTemplate = "templates/EntityVo.ftl"; //dto模版 public static final String entityDtoTemplate = "templates/EntityDto.ftl"; //pom模版 public static final String pomTemplate = "templates/pom.ftl"; //application.yml模版 public static final String applicationTemplate = "templates/application.ftl"; }
4.2.2 工具类
(1)DbUtil数据库工具类
package freemarker.util; import freemarker.param.ColumnClass; import freemarker.param.TableClass; import lombok.Getter; import lombok.Setter; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * 数据库工具类 */ @Setter @Getter public class DbUtil { //数据库连接地址 private String url = "jdbc:mysql://localhost:3306/heima_leadnews_wemedia?useSSL=false&nullCatalogMeansCurrent=true&serverTimezone=UTC"; //数据库用户名 private String username = "root"; //数据库密码 private String password = ""; //数据库驱动 private String driver = "com.mysql.jdbc.Driver"; //数据库名称 private String dbName = null; private Connection connection =null; /** * 获取jdbc链接 * @return * @throws Exception */ public Connection getConnection() throws Exception{ Properties pro = new Properties(); pro.setProperty("user", username); pro.setProperty("password", password); pro.put("useInformationSchema", "true");//获取mysql表注释 //pro.setProperty("remarksReporting","true");//获取oracle表注释 Class.forName(driver); connection = DriverManager.getConnection(url, pro); return connection; } /** * 获取当前数据库下的所有表名称及注释 * @return * @throws Exception */ public List<TableClass> getAllTables() throws Exception { List<TableClass> list = new ArrayList<>(); //获取链接 Connection conn = getConnection(); //获取元数据 DatabaseMetaData metaData = conn.getMetaData(); //获取所有的数据库表信息 ResultSet rs = metaData.getTables(dbName!=null?dbName:conn.getCatalog(), "%", "%", new String[]{"TABLE"}); while (rs.next()) { TableClass tableClass = new TableClass(); tableClass.setTableName(rs.getString(3)); tableClass.setTableComment(rs.getString(5)); list.add(tableClass); } return list; } /** * 获取某张表的所有列 * @param tableName * @return * @throws Exception */ public List<ColumnClass> getAllColumns(String tableName) throws Exception { List<ColumnClass> list = new ArrayList<>(); //获取链接 Connection conn = getConnection(); //获取元数据 DatabaseMetaData metaData = conn.getMetaData(); //获取所有的数据库某张表所有列信息 ResultSet rs = metaData.getColumns(dbName!=null?dbName:conn.getCatalog(), "%", tableName,"%"); while(rs.next()) { ColumnClass columnClass = new ColumnClass(); columnClass.setColumnName(rs.getString("COLUMN_NAME")); columnClass.setColumnType(rs.getString("TYPE_NAME")); columnClass.setColumnComment(rs.getString("REMARKS")); columnClass.setChangeColumnName(StrUtil.changeColumnStr(rs.getString("COLUMN_NAME"))); list.add(columnClass); } return list; } /** * 关闭链接 */ public void closeConnection(){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } }; }
(2)字符串处理工具类
package freemarker.util; /** * 字符串处理工具类 */ public class StrUtil { /** * 去掉下划线转驼峰 user_name -> userName * @param str * @return */ public static String changeColumnStr(String str) { String name = str; if (name.indexOf("_") > 0 && name.length() != name.indexOf("_") + 1) { int lengthPlace = name.indexOf("_"); name = name.replaceFirst("_", ""); String s = name.substring(lengthPlace, lengthPlace + 1); s = s.toUpperCase(); str = name.substring(0, lengthPlace) + s + name.substring(lengthPlace + 1); } else { return str; } return changeColumnStr(str); } /** * 去掉下划线转驼峰 tb_user -> TbUser * @param str * @return */ public static String changeTableStr(String str) { String s = changeColumnStr(str); return s.substring(0,1).toUpperCase()+s.substring(1); } }
(3)FreeMarker模版工具类
package freemarker.util; import freemarker.cache.FileTemplateLoader; import freemarker.cache.NullCacheStorage; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * FreeMarker模版工具类 */ public class FreeMarkerTemplateUtils { private FreeMarkerTemplateUtils(){} private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22); static{ //ClassTemplateLoader方式:需要将模版放在FreeMarkerTemplateUtils类所在的包,加载模版时会从该包下加载 //CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class,"")); try { String path = java.net.URLDecoder.decode(FreeMarkerTemplateUtils.class.getClassLoader().getResource("").getPath(),"utf-8"); //FileTemplateLoader方式:需要将模版放置在classpath目录下 目录有中文也可以 CONFIGURATION.setTemplateLoader(new FileTemplateLoader(new File(path))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } CONFIGURATION.setDefaultEncoding("UTF-8"); CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE); } public static Template getTemplate(String templateName) throws IOException { try { return CONFIGURATION.getTemplate(templateName); } catch (IOException e) { throw e; } } public static void clearCache() { CONFIGURATION.clearTemplateCache(); } }
4.2.3 实体类
(1)表实体类
package freemarker.param; import lombok.Data; @Data public class TableClass { /** * 表名 tb_user **/ private String tableName; /** * 表注释 **/ private String tableComment; }
(2)列实体类
package freemarker.param; import lombok.Data; @Data public class ColumnClass { /** * 数据库字段名称 user_name **/ private String columnName; /** * 数据库字段类型 **/ private String columnType; /** * 数据库字段首字母小写且去掉下划线字符串 userName **/ private String changeColumnName; /** * 数据库字段注释 **/ private String columnComment; }
(3)模版相关参数类
package freemarker.param; import lombok.Data; import org.apache.commons.lang3.StringUtils; import java.text.SimpleDateFormat; import java.util.Date; @Data public class TemplatePathParam { private String currentDate = new SimpleDateFormat("yyyy/MM/dd").format(new Date()); //包名 com.itheima.user private String packageName; //代码生成路径 D:\\path private String basePath; //项目名称 英文 比如itheima-user private String projectName; //作者 private String author ; //实体类生成的绝对路径 private String entityPath; //vo实体类生成的绝对路径 private String entityVoPath; //Dto实体类生成的绝对路径 private String entityDtoPath; //mapper生成绝对路径 private String mapperPath; //mapper映射文件生成的绝对路径 private String mapperXmlPath; //service接口生成的绝对路径 private String servicePath; //service实现类生成的绝对路径 private String serviceImplPath; //controller生成的绝对路径 private String controllerPath; //pom文件生成的绝对路径 private String pomPath; //application.yml文件生成的绝对路径 private String applicationYmlPath; public TemplatePathParam(String packageName, String basePath, String projectName, String author) { if(StringUtils.isBlank(packageName) || StringUtils.isBlank(basePath) || StringUtils.isBlank(author) || StringUtils.isBlank(projectName)){ throw new RuntimeException("参数不能为空"); } this.packageName = packageName; this.basePath = basePath; this.author = author; this.projectName = projectName; String[] split = packageName.split("\\."); // D:\\path\\itheima-user\\src\\main\\java\\com\\itheima\\user String javaModelPath = basePath+"\\"+projectName+"\\src\\main\\java\\"+split[0]+"\\"+split[1]+"\\"+split[2]; String xmlModelPath = basePath+"\\"+projectName+"\\src\\main\\resources\\"+split[0]+"\\"+split[1]+"\\"+split[2]; this.setEntityPath(javaModelPath+"\\entity"); this.setMapperPath(javaModelPath+"\\mapper"); this.setMapperXmlPath(xmlModelPath+"\\mapper"); this.setServicePath(javaModelPath+"\\service"); this.setServiceImplPath(javaModelPath+"\\service\\impl"); this.setControllerPath(javaModelPath+"\\http\\controller"); this.setEntityVoPath(javaModelPath+"\\http\\vo"); this.setEntityDtoPath(javaModelPath+"\\http\\dto"); this.setEntityDtoPath(javaModelPath+"\\http\\dto"); this.setPomPath(basePath+"\\"+projectName); this.setApplicationYmlPath(basePath+"\\"+projectName+"\\src\\main\\resources"); } }
4.2.4 代码生成器入口类
package freemarker; import freemarker.constant.TemplateConstant; import freemarker.param.ColumnClass; import freemarker.param.TableClass; import freemarker.param.TemplatePathParam; import freemarker.template.Template; import freemarker.util.DbUtil; import freemarker.util.FreeMarkerTemplateUtils; import freemarker.util.StrUtil; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 代码生成器入口 */ public class CodeGenerateUtils { private TemplatePathParam templatePathParam = null; public static void main(String[] args) throws Exception{ CodeGenerateUtils codeGenerateUtils = new CodeGenerateUtils(); codeGenerateUtils.generate(); System.out.println("============ 全部生成完成! ============="); } public void generate() throws Exception{ /** * 参数1:报名 * 参数2:生成代码的基础路径 * 参数3:项目名称 * 参数4:作者 */ templatePathParam = new TemplatePathParam("com.itheima.wemedia", "D:\\heima\\技术文章\\代码", "itheima-wemedia", "kdm"); //数据库相关 DbUtil dbUtil = new DbUtil(); //获取所有表 List<TableClass> allTable = dbUtil.getAllTables(); for (TableClass tableClass : allTable) { //表名 String table = tableClass.getTableName(); //获取所有列 List<ColumnClass> allColumns = dbUtil.getAllColumns(table); System.out.println("-------- 正在生成 " + table+" 表相关文件------"); //生成实体类 System.out.println("生成实体类"); generateEntityFile(tableClass, allColumns); //生成Mapper System.out.println("生成Mapper"); generateMapperFile(tableClass, allColumns); //生成Mapper.xml System.out.println("生成Mapper映射文件"); generateMapperXmlFile(tableClass, allColumns); //生成service接口 System.out.println("生成service接口"); generateServiceFile(tableClass, allColumns); //生成service实现类 System.out.println("生成service实现类"); generateServiceImplFile(tableClass, allColumns); //生成Controller层文件 System.out.println("生成Controller层文件"); generateControllerFile(tableClass, allColumns); //生成vo类 System.out.println("生成vo类"); generateEntityVoFile(tableClass, allColumns); //生成dto类 System.out.println("生成dto类"); generateEntityDtoFile(tableClass, allColumns); //生成pom文件 System.out.println("生成pom文件"); generatePomFile(tableClass, allColumns); //生成application.yml文件 System.out.println("生成application.yml文件"); generateApplicationYmlFile(tableClass, allColumns); } dbUtil.closeConnection(); } /** * 生成实体文件 */ private void generateEntityFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = ".java"; String filePath = templatePathParam.getEntityPath(); String file = templatePathParam.getEntityPath() + "\\"+ StrUtil.changeTableStr(tableClass.getTableName()) + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap.put("model_column",allColumns); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.entityTemplate, filePath, file, dataMap); } /** * 生成mapper文件 */ private void generateMapperFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "Mapper.java"; String filePath = templatePathParam.getMapperPath(); String file = templatePathParam.getMapperPath() + "\\"+ StrUtil.changeTableStr(tableClass.getTableName()) + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.mapperTemplate, filePath, file, dataMap); } /** * 生成xml映射文件 */ private void generateMapperXmlFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "Mapper.xml"; String filePath = templatePathParam.getMapperXmlPath(); String file = templatePathParam.getMapperXmlPath() + "\\"+ StrUtil.changeTableStr(tableClass.getTableName()) + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.mapperXmlTemplate, filePath, file, dataMap); } /** * 生成业务接口层 */ private void generateServiceFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "Service.java"; String filePath = templatePathParam.getServicePath(); String file = templatePathParam.getServicePath() + "\\"+ StrUtil.changeTableStr(tableClass.getTableName()) + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.serviceTemplate, filePath, file, dataMap); } /** * 生成业务实现层 */ private void generateServiceImplFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "ServiceImpl.java"; String filePath = templatePathParam.getServiceImplPath(); String file = templatePathParam.getServiceImplPath() + "\\"+ StrUtil.changeTableStr(tableClass.getTableName()) + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.serviceImplTemplate, filePath, file, dataMap); } /** * 生成控制层 */ private void generateControllerFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "Controller.java"; String filePath = templatePathParam.getControllerPath(); String file = templatePathParam.getControllerPath() + "\\"+ StrUtil.changeTableStr(tableClass.getTableName()) + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.controllerTemplate, filePath, file, dataMap); } /** * 生成Vo类 */ private void generateEntityVoFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "Vo.java"; String filePath = templatePathParam.getEntityVoPath(); String file = templatePathParam.getEntityVoPath() + "\\"+ StrUtil.changeTableStr(tableClass.getTableName()) + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap.put("model_column",allColumns); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.entityVoTemplate, filePath, file, dataMap); } /** * 生成Dto类 */ private void generateEntityDtoFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "Dto.java"; String filePath = templatePathParam.getEntityDtoPath(); String file = templatePathParam.getEntityDtoPath() + "\\"+ StrUtil.changeTableStr(tableClass.getTableName()) + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap.put("model_column",allColumns); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.entityDtoTemplate, filePath, file, dataMap); } /** * 生成Pom文件 */ private void generatePomFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "pom.xml"; String filePath = templatePathParam.getPomPath(); String file = templatePathParam.getPomPath() + "\\" + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.pomTemplate, filePath, file, dataMap); } /** * 生成application.yml文件 */ private void generateApplicationYmlFile(TableClass tableClass, List<ColumnClass> allColumns) throws Exception{ String suffix = "application.yml"; String filePath = templatePathParam.getApplicationYmlPath(); String file = templatePathParam.getApplicationYmlPath() + "\\" + suffix; Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap = getCommonModel(dataMap, tableClass); generateFileByTemplate(TemplateConstant.applicationTemplate, filePath, file, dataMap); } /** * 模版通用参数 * @param dataMap 模型map * @param tableClass 表名和表注释参数 * @return */ public Map<String,Object> getCommonModel(Map<String,Object> dataMap, TableClass tableClass){ dataMap.put("table_name", StrUtil.changeTableStr(tableClass.getTableName()));//TbUser dataMap.put("table_name_small",StrUtil.changeColumnStr(tableClass.getTableName()));//tbUser dataMap.put("table",tableClass.getTableName());//tb_user dataMap.put("author",templatePathParam.getAuthor()); dataMap.put("date",templatePathParam.getCurrentDate()); dataMap.put("package_name",templatePathParam.getPackageName()); dataMap.put("project_name",templatePathParam.getProjectName()); dataMap.put("table_annotation", StringUtils.isNotBlank(tableClass.getTableComment()) ? tableClass.getTableComment() : null); return dataMap; } /** * 静态化方法 * @param templateName 模版名称 * @param filePathParam 文件所在目录 绝对路径 * @param fileParam 文件 绝对路径 * @param dataMap 数据模型 * @throws Exception */ private void generateFileByTemplate(final String templateName, String filePathParam, String fileParam, Map<String,Object> dataMap) throws Exception{ Template template = FreeMarkerTemplateUtils.getTemplate(templateName); System.out.println(fileParam); //文件夹不存在创建文件夹 File filePath = new File(filePathParam); if (!filePath.exists() && !filePath.isDirectory()) { filePath.mkdirs(); } //文件不存在创建文件夹 File file = new File(fileParam); if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileOutputStream fos = new FileOutputStream(file); Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240); template.process(dataMap,out); } }
5 制作通用模版
在 resources/templates 目录下创建模版类
5.1 实体类模版
package ${package_name}.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.ToString; import java.util.Date; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 描述:<#if table_annotation??>${table_annotation}模型</#if> * @author ${author} * @date ${date} */ @Data @ToString(callSuper = true) @TableName("${table}") public class ${table_name} implements Serializable { <#if model_column?exists> <#list model_column as model> /** * ${model.columnComment!} */ <#if (model.columnType = 'BIGINT' && model.columnName = 'id')> @TableId("${model.columnName?uncap_first}") private Long ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'BIGINT' && model.columnName != 'id')> @TableField("${model.columnName?uncap_first}") private Long ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'INT' || model.columnType = 'INT UNSIGNED' || model.columnType = 'TINYINT' || model.columnType = 'TINYINT UNSIGNED')> @TableField("${model.columnName?uncap_first}") private Integer ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'DECIMAL')> @TableField("${model.columnName?uncap_first}") private BigDecimal ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'VARCHAR' || model.columnType = 'TEXT' || model.columnType = 'CHAR')> @TableField("${model.columnName?uncap_first}") private String ${model.changeColumnName?uncap_first}; </#if> <#if model.columnType = 'TIMESTAMP' || model.columnType = 'YEAR' || model.columnType = 'DATE' || model.columnType = 'DATETIME' > @TableField("${model.columnName?uncap_first}") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8") private Date ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType != 'BIGINT' && model.columnType != 'INT' && model.columnType != 'DECIMAL' && model.columnType != 'VARCHAR' && model.columnType != 'TEXT' && model.columnType != 'CHAR' && model.columnType != 'TIMESTAMP' && model.columnType != 'YEAR' && model.columnType != 'DATE' && model.columnType != 'DATETIME' && model.columnType != 'INT UNSIGNED' && model.columnType != 'TINYINT' && model.columnType != 'TINYINT UNSIGNED')> @TableField("${model.columnName?uncap_first}") private MISS ${model.changeColumnName?uncap_first}; </#if> </#list> </#if> }
5.2 Mapper模版
package ${package_name}.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import ${package_name}.entity.${table_name}; import org.apache.ibatis.annotations.Mapper; /** * 描述:<#if table_annotation??>${table_annotation}数据库连接层</#if> * @author ${author} * @date ${date} */ @Mapper public interface ${table_name}Mapper extends BaseMapper<${table_name}> { }
5.3 Mapper映射文件模版
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="${package_name}.mapper.${table_name}Mapper"> </mapper>
5.4 Service接口模版
package ${package_name}.service; import ${package_name}.entity.${table_name}; import com.baomidou.mybatisplus.extension.service.IService; /** * 描述:<#if table_annotation??>${table_annotation}服务实现层接口</#if> * @author ${author} * @date ${date} */ public interface ${table_name}Service extends IService<${table_name}>{ }
5.5 Service实现类模版
package ${package_name}.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import ${package_name}.entity.${table_name}; import ${package_name}.service.${table_name}Service; import ${package_name}.mapper.${table_name}Mapper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; /** * 描述:<#if table_annotation??>${table_annotation}服务实现层</#if> * @author ${author} * @date ${date} */ @Slf4j @Service public class ${table_name}ServiceImpl extends ServiceImpl<${table_name}Mapper, ${table_name}> implements ${table_name}Service{ }
5.6 Controller模版
package ${package_name}.http.controller; import org.springframework.web.bind.annotation.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.BeanUtils; import org.springframework.validation.annotation.Validated; import ${package_name}.entity.${table_name}; import ${package_name}.service.${table_name}Service; import ${package_name}.http.vo.${table_name}Vo; import ${package_name}.http.dto.${table_name}Dto; import java.util.List; /** * 描述:<#if table_annotation??>${table_annotation}控制层</#if> * @author ${author} * @date ${date} */ @RestController @RequestMapping("/${table_name_small}") public class ${table_name}Controller { @Autowired private ${table_name}Service ${table_name_small}Service; /** * 查询所有 */ @GetMapping public List<${table_name}> list(){ return ${table_name_small}Service.list(); } /** * 查询一个 */ @GetMapping("/{id}") public ${table_name} get(@PathVariable Long id){ return ${table_name_small}Service.getById(id); } /** * 新增 */ @PostMapping public boolean save(@Validated @RequestBody ${table_name}Dto ${table_name_small}Dto){ ${table_name} ${table_name_small} = new ${table_name}(); BeanUtils.copyProperties(${table_name_small}Dto, ${table_name_small}); return ${table_name_small}Service.save(${table_name_small}); } /** * 修改 */ @PutMapping public boolean update(@Validated @RequestBody ${table_name}Dto ${table_name_small}Dto){ ${table_name} ${table_name_small} = new ${table_name}(); BeanUtils.copyProperties(${table_name_small}Dto, ${table_name_small}); return ${table_name_small}Service.updateById(${table_name_small}); } /** * 删除 * @param id * @return 是否成功 */ @DeleteMapping("/{id}") public boolean del(@PathVariable Long id){ return ${table_name_small}Service.removeById(id); } }
5.7 实体类Vo模版
package ${package_name}.http.vo; import java.io.Serializable; import java.util.Date; import lombok.Data; import lombok.ToString; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; /** * 描述:<#if table_annotation??>${table_annotation}模型</#if>Vo类 * @author ${author} * @date ${date} */ @Data @ToString(callSuper = true) public class ${table_name}Vo implements Serializable { <#if model_column?exists> <#list model_column as model> <#if (model.columnType = 'BIGINT' && model.columnName = 'id')> @JsonSerialize(using = ToStringSerializer.class) private Long ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'BIGINT' && model.columnName != 'id')> private Long ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'INT' || model.columnType = 'INT UNSIGNED' || model.columnType = 'TINYINT')> private Integer ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'DECIMAL')> private BigDecimal ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'VARCHAR' || model.columnType = 'TEXT' || model.columnType = 'CHAR')> private String ${model.changeColumnName?uncap_first}; </#if> <#if model.columnType = 'TIMESTAMP' || model.columnType = 'YEAR' || model.columnType = 'DATE' || model.columnType = 'DATETIME' > @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8") private Date ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType != 'BIGINT' && model.columnType != 'INT' && model.columnType != 'VARCHAR' && model.columnType != 'DECIMAL' && model.columnType != 'TEXT' && model.columnType != 'CHAR' && model.columnType != 'TIMESTAMP' && model.columnType != 'YEAR' && model.columnType != 'DATE' && model.columnType != 'DATETIME' && model.columnType != 'INT UNSIGNED')> private MISS ${model.changeColumnName?uncap_first}; </#if> </#list> </#if> }
5.8 实体类Dto模版
package ${package_name}.http.dto; import java.io.Serializable; import java.util.Date; import lombok.Data; import lombok.ToString; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.annotation.JsonFormat; /** * 描述:<#if table_annotation??>${table_annotation}模型</#if>Dto类 * @author ${author} * @date ${date} */ @Data @ToString(callSuper = true) public class ${table_name}Dto implements Serializable { <#if model_column?exists> <#list model_column as model> <#if (model.columnType = 'BIGINT' && model.columnName = 'id')> @JsonSerialize(using = ToStringSerializer.class) private Long ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'BIGINT' && model.columnName != 'id')> private Long ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'INT' || model.columnType = 'INT UNSIGNED' || model.columnType = 'TINYINT')> private Integer ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'DECIMAL')> private BigDecimal ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType = 'VARCHAR' || model.columnType = 'TEXT' || model.columnType = 'CHAR')> private String ${model.changeColumnName?uncap_first}; </#if> <#if model.columnType = 'TIMESTAMP' || model.columnType = 'YEAR' || model.columnType = 'DATE' || model.columnType = 'DATETIME' > @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8") private Date ${model.changeColumnName?uncap_first}; </#if> <#if (model.columnType != 'BIGINT' && model.columnType != 'INT' && model.columnType != 'VARCHAR' && model.columnType != 'DECIMAL' && model.columnType != 'TEXT' && model.columnType != 'CHAR' && model.columnType != 'TIMESTAMP' && model.columnType != 'YEAR' && model.columnType != 'DATE' && model.columnType != 'DATETIME' && model.columnType != 'INT UNSIGNED')> private MISS ${model.changeColumnName?uncap_first}; </#if> </#list> </#if> }
5.9 pom文件模版
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>${package_name}</groupId> <artifactId>${project_name}</artifactId> <version>1.0-SNAPSHOT</version> <!-- 继承Spring boot工程 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.9.RELEASE</version> </parent> <properties> <!-- 项目源码及编译输出的编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- 项目编译JDK版本 --> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <!-- 依赖包版本管理 --> <spring.boot.version>2.3.9.RELEASE</spring.boot.version> <lombok.version>1.18.8</lombok.version> <mysql.version>5.1.46</mysql.version> <mybatis-plus.version>3.3.1</mybatis-plus.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${r"${mybatis-plus.version}"}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${r"${mysql.version}"}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${r"${lombok.version}"}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.10</version> </dependency> </dependencies> </project>
5.10 application.yml文件模版
server: port: ${r"${port:8888}"} spring: application: name: ${project_name}
6 测试
运行代码生成器入口类 CodeGenerateUtils
输出日志如下
D:\app\devs\Java\jdk-11\bin\java.exe "-javaagent:D:\app\devs\JetBrains\IntelliJ IDEA 2018.2.4\lib\idea_rt.jar=60577:D:\app\devs\JetBrains\IntelliJ IDEA 2018.2.4\bin" -Dfile.encoding=UTF-8 -classpath D:\heima\技术文章\itheima-code\target\classes;D:\app\devs\apache-maven-3.3.9\maven_repository\org\freemarker\freemarker\2.3.23\freemarker-2.3.23.jar;D:\app\devs\apache-maven-3.3.9\maven_repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;D:\app\devs\apache-maven-3.3.9\maven_repository\org\projectlombok\lombok\1.18.8\lombok-1.18.8.jar;D:\app\devs\apache-maven-3.3.9\maven_repository\org\apache\commons\commons-lang3\3.10\commons-lang3-3.10.jar freemarker.CodeGenerateUtils -------- 正在生成 undo_log 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\UndoLog.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\UndoLogMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\UndoLogMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\UndoLogService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\UndoLogServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\UndoLogController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\UndoLogVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\UndoLogDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml -------- 正在生成 wm_channel 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\WmChannel.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\WmChannelMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\WmChannelMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\WmChannelService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\WmChannelServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\WmChannelController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\WmChannelVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\WmChannelDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml -------- 正在生成 wm_fans_statistics 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\WmFansStatistics.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\WmFansStatisticsMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\WmFansStatisticsMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\WmFansStatisticsService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\WmFansStatisticsServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\WmFansStatisticsController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\WmFansStatisticsVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\WmFansStatisticsDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml -------- 正在生成 wm_material 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\WmMaterial.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\WmMaterialMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\WmMaterialMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\WmMaterialService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\WmMaterialServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\WmMaterialController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\WmMaterialVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\WmMaterialDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml -------- 正在生成 wm_news 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\WmNews.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\WmNewsMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\WmNewsMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\WmNewsService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\WmNewsServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\WmNewsController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\WmNewsVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\WmNewsDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml -------- 正在生成 wm_news_material 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\WmNewsMaterial.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\WmNewsMaterialMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\WmNewsMaterialMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\WmNewsMaterialService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\WmNewsMaterialServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\WmNewsMaterialController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\WmNewsMaterialVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\WmNewsMaterialDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml -------- 正在生成 wm_news_statistics 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\WmNewsStatistics.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\WmNewsStatisticsMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\WmNewsStatisticsMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\WmNewsStatisticsService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\WmNewsStatisticsServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\WmNewsStatisticsController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\WmNewsStatisticsVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\WmNewsStatisticsDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml -------- 正在生成 wm_sensitive 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\WmSensitive.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\WmSensitiveMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\WmSensitiveMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\WmSensitiveService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\WmSensitiveServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\WmSensitiveController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\WmSensitiveVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\WmSensitiveDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml -------- 正在生成 wm_user 表相关文件------ 生成实体类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\entity\WmUser.java 生成Mapper D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\mapper\WmUserMapper.java 生成Mapper映射文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\com\itheima\wemedia\mapper\WmUserMapper.xml 生成service接口 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\WmUserService.java 生成service实现类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\service\impl\WmUserServiceImpl.java 生成Controller层文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\controller\WmUserController.java 生成vo类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\vo\WmUserVo.java 生成dto类 D:\heima\技术文章\代码\itheima-wemedia\src\main\java\com\itheima\wemedia\http\dto\WmUserDto.java 生成pom文件 D:\heima\技术文章\代码\itheima-wemedia\pom.xml 生成application.yml文件 D:\heima\技术文章\代码\itheima-wemedia\src\main\resources\application.yml ============ 全部生成完成! ============= Process finished with exit code 0
在idea中点击 File > open 打开 D:\heima\技术文章\代码\itheima-wemedia
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/47687.html