首页 > 其他分享 >Code Generate 代码生成器 V1.0

Code Generate 代码生成器 V1.0

时间:2023-03-14 14:56:23浏览次数:46  
标签:代码生成 Code return String params result put new Generate

Code Generate V1.0 代码生成器

根据配置的模板,根据建表语句,生成Code。

例如java代码、vue代码、jsp代码以及html代码等等,均可根据自己的代码写作习惯进行配置。

缺点:配置的模板,需要在工程里面写死,不够灵活。

页面

Java

包括常用 Controller、Service、Mapper、Entity;

Vue

以Element-UI代码为例,表格、增加、删除、修改;

themyleaf

基于Layui 表格、增加、删除、修改;

Jsp

基于Layui 表格、增加、删除、修改;

测试样例

建表语句


CREATE TABLE `course`
(
    `id`          int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `course_no`   int(11) DEFAULT NULL COMMENT '课程编号',
    `course_name` varchar(255) DEFAULT NULL COMMENT '课程名称',
    `create_time` datetime     DEFAULT NULL COMMENT '创建时间',
    `creator`     varchar(255) DEFAULT NULL COMMENT '创建人',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

测试

以生成Java实体类为例

package ${packageName}.entity;

import java.util.Date;

import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;

import java.io.Serializable;

/**
* (${className})表实体类
*
* @author ${author}
* @since ${date}
*/
@Data
public class ${className} extends Model<${className}> {
    <#list fieldList as field>
        /**
        * ${field.comment}
        */
        private ${field.type} ${field.name};
    </#list>
}

Result

package com.java.entity;

import java.util.Date;

import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;

import java.io.Serializable;

/**
* (Course)表实体类
*
* @author HelloWorld
* @since 2023-03-14 14:38:05
*/
@Data
public class Course extends Model<Course> {
        /**
        * 主键ID
        */
        private Integer id;
        /**
        * 课程编号
        */
        private Integer courseNo;
        /**
        * 课程名称
        */
        private String courseName;
        /**
        * 创建时间
        */
        private Date createTime;
        /**
        * 创建人
        */
        private String creator;
}

Code

依赖

只列出关键依赖

  <!--freemarker依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

TemplateService.java


@Service
public class TemplateService {

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 统一 返回代码段
     *
     * @param tem 模板实体
     * @return
     * @throws IOException
     */
    public String commonReturnCode(TemplateEntity tem) throws IOException {
        //template:resource目录下的ftl文件放置目录
        SpringTemplateLoader templateLoader = new SpringTemplateLoader(resourceLoader, "classpath:templates");
        // 创建配置实例
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        // 设置编码
        configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
        configuration.setTemplateLoader(templateLoader);
        try {
            // 获取模板
            Template template = configuration.getTemplate(tem.getTemplatePath()+tem.getTemplateName());
            StringWriter writer = new StringWriter();
            template.process(tem.getParams(), writer);
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

GenerateService.java

@Service
public class GenerateService {

    @Resource
    private TemplateService templateService;


    /**
     * 生成java代码
     *
     * @param typeList  需要的类型 例如 1:entity 2:mapper 等等
     * @return
     */
    public  Result generateJavaCode(String sql ,String author,String packageName, List<Integer> typeList) {
        // 接收结果
        Map<String, String> result = new HashMap<>();

        POJOmaker pojOmaker = ResolveSqlUtil.resolve(sql,"","",packageName,author);
        Map<String, Object> params = new HashMap<>();
        // 作者名
        params.put("author",author);
        // 类名
        params.put("className",pojOmaker.getClassName());
        // 字段集
        params.put("fieldList",pojOmaker.getFieldList());
        // 包名
        params.put("packageName",pojOmaker.getPackageName());
        // 创建时间
        params.put("date",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        

        typeList.forEach(type -> {
            // 实体类
            if (type == ENTITY_TYPE) {
                String code = "";
                try {
                     code = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_JAVA,"Entity.java.ftl"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                result.put("entity",code);
            }
            // Mapper 层
            if (type == MAPPER_TYPE) {
                String code = "";
                try {
                    code = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_JAVA,"Mapper.java.ftl"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                result.put("mapper",code);
            }

            // service层
            if (type == SERVICE_TYPE) {
                String code = "";
                try {
                    code = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_JAVA,"Service.java.ftl"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                result.put("service",code);
            }
            // serviceImpl 实现
            if (type == SERVICE_IMPL_TYPE) {
                String code = "";
                try {
                    code = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_JAVA,"ServiceImpl.java.ftl"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                result.put("serviceImpl",code);
            }
            // controller
            if (type == CONTROLLER_TYPE) {
                String code = "";
                try {
                    code = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_JAVA,"Controller.java.ftl"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                result.put("controller",code);
            }
        });
        return Result.success("success",result);
    }

    /**
     * 生成vue 代码
     * @return
     */
    public  Result generateVueCode(String sql){
        POJOmaker pojOmaker = ResolveSqlUtil.resolve(sql,"","","","");
        // 接收结果
        Map<String, String> result = new HashMap<>();
        // 参数
        Map<String, Object> params = new HashMap<>();
        // 字段
        params.put("fieldList",pojOmaker.getFieldList());
        // 类名
        params.put("className",pojOmaker.getClassName());
        // 生成表格
        String vue = "";
        try {
            vue = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_VUE,"Table.vue.ftl"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        result.put("vue",vue);

        // 生成弹窗
        String dialog = "";
        try {
            dialog = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_VUE,"Dialog.vue.ftl"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        result.put("dialog",dialog);
        return Result.success("success",result);
    }


    /**
     * 生成JSP代码
     * @return
     */
    public  Result generateJspCode(String sql,String author){
        POJOmaker pojOmaker = ResolveSqlUtil.resolve(sql,"","","","");
        // 接收结果
        Map<String, String> result = new HashMap<>();
        // 参数
        Map<String, Object> params = new HashMap<>();
        // 字段
        params.put("fieldList",pojOmaker.getFieldList());
        // 类名
        params.put("className",pojOmaker.getClassName());
        // 作者名
        params.put("author",author);
        // 创建时间
        params.put("date",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        // 生成表格
        String html = "";
        try {
            html = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_JSP,"index.jsp.ftl"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        result.put("jsp",html);

        // 生成弹窗
        String js = "";
        try {
            js = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_JSP,"index.js.ftl"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        result.put("js",js);
        return Result.success("success",result);
    }


    /**
     * 生成ThemyLeaf 代码
     * @return
     */
    public  Result generateThemyLeafCode(String sql){
        POJOmaker pojOmaker = ResolveSqlUtil.resolve(sql,"","","","");
        // 接收结果
        Map<String, String> result = new HashMap<>();
        // 参数
        Map<String, Object> params = new HashMap<>();
        // 字段
        params.put("fieldList",pojOmaker.getFieldList());
        // 类名
        params.put("className",pojOmaker.getClassName());
        // 生成表格
        String html = "";
        try {
            html = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_THEMYLEAF,"index.html.ftl"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        result.put("html",html);

        // 生成弹窗
        String js = "";
        try {
            js = templateService.commonReturnCode(new TemplateEntity(params,TEMPLATE_THEMYLEAF,"index.js.ftl"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        result.put("js",js);
        return Result.success("success",result);
    }



    /**
     * mapper 在系统内部
     */
    public void generateMapper() {
        Configuration configuration = new Configuration(new Version("2.3.3"));
        configuration.setDefaultEncoding("utf-8");
        String absolutePath = System.getProperty("user.dir") + "\\src\\main\\resources\\templates";
        try {
            // 加载.ftl配置文件所在路径
            configuration.setDirectoryForTemplateLoading(new File(absolutePath));
            // 放模板变量的值
            Map<String, Object> params = new HashMap<>();
            params.put("package", "io.demo.generator");
            params.put("mapper", "dao");
            params.put("author", "xxx");
            params.put("date", "2022-06-03");
            params.put("comments", "freemarker模板");
            params.put("className", "GenerateFile");
            params.put("mapperSuffix", "Mapper");
            //给文件赋值
            Template template = configuration.getTemplate("Mapper.java.ftl");
            // 文件输出路径
            FileOutputStream file = new FileOutputStream("C:\\Users\\最可爱的WXQ\\Desktop\\文件资源\\GenerateFileMapper.java");
            OutputStreamWriter out = new OutputStreamWriter(file, "utf-8");
            template.process(params, out);
            out.close();
        } catch (IOException | TemplateException exception) {
            exception.printStackTrace();
        }
    }
}

GenerateController.java

/**
 * Code 接口
 */
@RestController
@RequestMapping("code")
public class GenerateController {


    @Resource
    private GenerateService generateService;

    /**
     * 生成java代码
     *
     * @return
     */
    @PostMapping("/generateJavaCode")
    public Result generateJava(@RequestBody BaseInfo baseInfo) {
        return generateService.generateJavaCode(baseInfo.getSql(), baseInfo.getAuthor(), baseInfo.getPackageName(), baseInfo.getType());
    }


    /**
     * 生成Vue Code
     *
     * @return
     */
    @PostMapping("/generateVueCode")
    public Result generateVue(@RequestBody BaseInfo baseInfo) {
        return generateService.generateVueCode(baseInfo.getSql());
    }

    /**
     * 生成ThemyLeaf Code
     *
     * @return
     */
    @PostMapping("/generateThemyLeafCode")
    public Result generateThemyLeaf(@RequestBody BaseInfo baseInfo) {
        return generateService.generateThemyLeafCode(baseInfo.getSql());
    }

    /**
     * 生成 JSP Code
     *
     * @return
     */
    @PostMapping("/generateJspCode")
    public Result generateJsp(@RequestBody BaseInfo baseInfo) {
        return generateService.generateJspCode(baseInfo.getSql(),baseInfo.getAuthor());
    }
}

前端的代码,只需要调用接口即可。

标签:代码生成,Code,return,String,params,result,put,new,Generate
From: https://www.cnblogs.com/HelloWxl/p/17214916.html

相关文章

  • vscode-vim键盘操作配置
    vscode(win)+vim键盘操作配置参考了知乎博主云崖君的vscode+vim全键盘操作高效搭配方案,仅用以记录个人使用配置,内容较为简略。配置文件如下详见后续说明。s......
  • [思维提升|干货All in]6种算法解决LeetCode困难题:滑动窗口最大值
    为了更好的阅读体验,欢迎阅读原文:[思维提升|干货Allin]6种算法解决LeetCode困难题:滑动窗口最大值(eriktse.com)最近在leetcode遇到一道非常经典的题目:239.滑动窗口最......
  • [LeetCode] 62. 不同路径 java 动态规划解法
    classSolution{publicintuniquePaths(intm,intn){//确定dp数组以及下标的含义//dp[i][j]:表⽰从(0,0)出发,到(i,j)有dp[i][j]条不同的路径......
  • atcoder ABC
    Ex-OptimalPathDecomposition题目只能给链染色,问你最短的(两点距离最大值),距离为不同颜色个数f[u],g[u],f表示u可以和father同一个颜色,g表示不可以。转移记录三个值。......
  • LeetCode142. 环形链表 II
    题目描述:给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。如果链表中有某个节点,可以通过连续跟踪next指针再次到达,则链表中......
  • 【LeetCode回溯算法#11】解数独,这次是真的用回溯法处理二维数组
    解数独力扣题目链接(opensnewwindow)编写一个程序,通过填充空格来解决数独问题。一个数独的解法需遵循如下规则:数字1-9在每一行只能出现一次。数字1-9在每一列只......
  • Transformer中的encoder与decoder
    Transformer是一种非常强大的神经网络架构,被广泛应用于自然语言处理任务中。它的核心部分是由若干个Encoder和Decoder组成的。下面简要介绍一下Encoder和Decoder的区别。......
  • vscode 创建 venv 项目(ubuntu下我个人的安装的一些过程)
    1.mkdirpr:创建项目文件夹cdpr进入项目文件夹中code.打开文件夹2.按ctrl+shift+p选择Python:CreateEnvironment,选择venv作为环境类型,然后选择默认的解释器位置......
  • codeforce 2000+练习
    ThreeSequences2200https://www.luogu.com.cn/problem/CF1406D题解:贪心地想,令x为答案,则x应该为b的末项和c的首项,而每一步a(i)->a(i+1)若上升则b上升,若下降则c下降。故......
  • [Leetcode Weekly Contest]336
    链接:LeetCode[Leetcode]2586.统计范围内的元音字符串数给你一个下标从0开始的字符串数组words和两个整数:left和right。如果字符串以元音字母开头并以元音字母结......