JPA代码生成器

news2024/10/6 16:25:27

【Java代码生成神器】自动化生成Java实体类、代码、增删改查功能!点击访问

推荐一个自己每天都在用的Java代码生成器!这个网站支持在线生成Java代码,包含完整的Controller\Service\Entity\Dao代码,完整的增删改查功能!

还可以自定义自己的代码模板、自由配置高级选项,指定是否集成Lombok和Swagger等常用库,一键生成,省去了大量时间和精力!
快来试试吧!在线地址
在这里插入图片描述
在这里插入图片描述

一款支持多种ORM框架的Java代码生成器,基于模板引擎实现,具有非常高的自由度,可随意修改为适合你的代码风格
支持JPA、Mybatis、MybatisPlus等ORM框架

以下为开源版本
源码:

  • 前端:https://github.com/dengweiping4j/code-generator-ui.git
  • 后端:https://github.com/dengweiping4j/CodeGenerator.git

界面展示:在这里插入图片描述
在这里插入图片描述

关键代码:

 package com.dwp.codegenerator.utils;

import com.dwp.codegenerator.domain.ColumnEntity;
import com.dwp.codegenerator.domain.DatabaseColumn;
import com.dwp.codegenerator.domain.GeneratorParams;
import com.dwp.codegenerator.domain.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class GeneratorUtil {

    /**
     * 生成代码
     *
     * @param generatorParams
     * @param zip
     */
    public static void generatorCode(GeneratorParams generatorParams, ZipOutputStream zip) {
        //参数处理
        TableEntity tableEntity = formatParams(generatorParams);
        //设置velocity资源加载器
        initVelocity();
        //封装模板数据
        VelocityContext context = getVelocityContext(generatorParams, tableEntity);
        //渲染模板
        apply(context, zip, tableEntity, generatorParams);
    }

    private static void apply(VelocityContext context, ZipOutputStream zip, TableEntity tableEntity, GeneratorParams generatorParams) {
        List<String> templates = getTemplates(generatorParams.getGeneratorType());
        templates.forEach(template -> {
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);
            try {
                String fileName = getFileName(template, tableEntity.getUpperClassName(), generatorParams);
                //添加到zip
                zip.putNextEntry(new ZipEntry(fileName));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException("渲染模板失败,表名:" + tableEntity.getTableName(), e);
            }
        });
    }

    /**
     * 使用自定义模板
     *
     * @param generatorType
     * @return
     */
    private static List<String> getTemplates(String generatorType) {
        List<String> templates = new ArrayList<>();
        switch (generatorType) {
            case "jpa":
                templates.add("template/jpa/Repository.java.vm");
                templates.add("template/jpa/Specifications.java.vm");
                templates.add("template/jpa/Service.java.vm");
                templates.add("template/jpa/Controller.java.vm");
                templates.add("template/jpa/Domain.java.vm");
                break;
            case "mybatis":
                templates.add("template/mybatis/Mapper.java.vm");
                templates.add("template/mybatis/Mapper.xml.vm");
                templates.add("template/mybatis/Service.java.vm");
                templates.add("template/mybatis/ServiceImpl.java.vm");
                templates.add("template/mybatis/Controller.java.vm");
                templates.add("template/mybatis/Entity.java.vm");
                templates.add("template/mybatis/EntityParam.java.vm");
                templates.add("template/mybatis/PageResult.java.vm");
                templates.add("template/mybatis/RestResp.java.vm");
                break;
            case "mybatis-plus":
                templates.add("template/mybatis-plus/Mapper.java.vm");
                templates.add("template/mybatis-plus/Mapper.xml.vm");
                templates.add("template/mybatis-plus/Service.java.vm");
                templates.add("template/mybatis-plus/ServiceImpl.java.vm");
                templates.add("template/mybatis-plus/Controller.java.vm");
                templates.add("template/mybatis-plus/Entity.java.vm");
                templates.add("template/mybatis-plus/EntityParam.java.vm");
                templates.add("template/mybatis-plus/PageResult.java.vm");
                templates.add("template/mybatis-plus/RestResp.java.vm");
                break;
        }
        return templates;
    }


    private static String getPackagePath(GeneratorParams generatorParams) {
        //配置信息
        Configuration config = getConfig();
        String packageName = StringUtils.isNotBlank(generatorParams.getPackageName())
                ? generatorParams.getPackageName()
                : config.getString("package");
        String moduleName = StringUtils.isNotBlank(generatorParams.getModuleName())
                ? generatorParams.getModuleName()
                : config.getString("moduleName");
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
        }
        return packagePath;
    }

    private static VelocityContext getVelocityContext(GeneratorParams generatorParams, TableEntity tableEntity) {
        Configuration config = getConfig();
        Map<String, Object> map = new HashMap<>();
        map.put("generatorType", generatorParams.getGeneratorType());
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getUpperClassName());
        map.put("classname", tableEntity.getLowerClassName());
        map.put("pathName", tableEntity.getLowerClassName().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("mainPath", StringUtils.isBlank(config.getString("mainPath")) ? "com.dwp" : config.getString("mainPath"));
        map.put("package", StringUtils.isNotBlank(generatorParams.getPackageName()) ? generatorParams.getPackageName() : config.getString("package"));
        map.put("moduleName", StringUtils.isNotBlank(generatorParams.getModuleName()) ? generatorParams.getModuleName() : config.getString("moduleName"));
        map.put("author", StringUtils.isNotBlank(generatorParams.getAuthor()) ? generatorParams.getAuthor() : config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        VelocityContext context = new VelocityContext(map);
        return context;
    }

    private static void initVelocity() {
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
    }

    /**
     * 表、字段参数处理
     *
     * @param generatorParams
     * @return
     */
    private static TableEntity formatParams(GeneratorParams generatorParams) {
        TableEntity tableEntity = new TableEntity();
        //表信息
        setTableEntity(tableEntity, generatorParams);
        //设置列信息
        setColumns(tableEntity, generatorParams);
        //没主键,则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }
        return tableEntity;
    }

    private static void setColumns(TableEntity tableEntity, GeneratorParams generatorParams) {
        List<ColumnEntity> columnsList = new ArrayList<>();
        for (DatabaseColumn column : generatorParams.getColumns()) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.getColumnName());
            //列名转换成Java属性名
            String attrName = columnToJava(column.getColumnName());
            columnEntity.setUpperAttrName(attrName);
            columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));
            columnEntity.setComments(column.getColumnComment());

            //列的数据类型,转换成Java类型
            Configuration config = getConfig();
            String attrType = config.getString(column.getColumnType(), "unknowType");
            columnEntity.setAttrType(attrType);
            //是否主键
            if (column.isPrimary()) {
                tableEntity.setPk(columnEntity);
            }
            columnsList.add(columnEntity);
        }
        tableEntity.setColumns(columnsList);
    }

    private static void setTableEntity(TableEntity tableEntity, GeneratorParams generatorParams) {
        tableEntity.setTableName(generatorParams.getTableName());
        tableEntity.setComments(generatorParams.getTableComment());
        //表名转换成Java类名
        Configuration config = getConfig();
        String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix"));
        tableEntity.setUpperClassName(className);
        tableEntity.setLowerClassName(StringUtils.uncapitalize(className));
    }

    /**
     * 列名转换成Java属性名
     */
    private static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    private static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    private static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置文件失败,", e);
        }
    }

    /**
     * 获取文件名
     */
    private static String getFileName(String templateName, String className, GeneratorParams generatorParams) {
        String packagePath = getPackagePath(generatorParams);
        if (StringUtils.isNotBlank(templateName)) {
            String afterClassName = templateName.substring(templateName.lastIndexOf("/") + 1, templateName.indexOf("."));
            if (templateName.contains("template/jpa/Specifications.java.vm")) {
                return packagePath + "repository" + File.separator + className + "Specifications.java";
            }
            if (templateName.endsWith("Mapper.xml.vm")) {
                return packagePath + afterClassName.toLowerCase() + File.separator + className + afterClassName + ".xml";
            }
            if (templateName.contains("template/jpa/Domain.java.vm")
                    || templateName.endsWith("Entity.java.vm")) {
                return packagePath + afterClassName.toLowerCase() + File.separator + className + ".java";
            }
            if (templateName.endsWith("EntityParam.java.vm")) {
                return packagePath + "entity/param" + File.separator + className + "Param.java";
            }
            if (templateName.endsWith("ServiceImpl.java.vm")) {
                return packagePath + "service/impl" + File.separator + className + afterClassName + ".java";
            }
            if (templateName.endsWith("PageResult.java.vm")) {
                return packagePath + "util" + File.separator + "PageResult.java";
            }
            if (templateName.endsWith("RestResp.java.vm")) {
                return packagePath + "util" + File.separator + "RestResp.java";
            }
            return packagePath + afterClassName.toLowerCase() + File.separator + className + afterClassName + ".java";
        }
        return null;
    }
}

项目地址:
前端:https://github.com/dengweiping4j/code-generator-ui.git
后端:https://github.com/dengweiping4j/CodeGenerator.git

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1270998.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Linux | Ubuntu设置 netstat(网络状态)

netstat命令用于显示与IP、TCP、UDP和ICMP协议相关的统计数据&#xff0c;一般用于检验本机各端口的网络连接情况。netstat是在内核中访问网络及相关信息的程序&#xff0c;它能提供TCP连接&#xff0c;TCP和UDP监听&#xff0c;进程内存管理的相关报告。 1.netstat的安装 搜…

自己的邮箱名称出现在别人的此电脑的网络位置中

在公司别的同事告诉我&#xff0c;我的邮箱名字出现在他们的【此电脑】-【网络位置中】 如图&#xff1a; 当时吓我一跳&#xff0c;因为我总喜欢搞一些渗透的东西&#xff0c;我以为把自己暴漏了&#xff0c;然后疯狂的在网上找原因。 于是就搜到一位安暖的博主&#xff1a; …

VSCode搭建STM32开发环境

1、下载安装文件 链接&#xff1a;https://pan.baidu.com/s/1WnpDTgYBobiZaXh80pn5FQ 2、安装VSCodeUserSetup-x64-1.78.2.exe软件 3、 在VSCode中安装必要的插件 3、配置Keil Assistant插件 4、在环境变量中部署mingw64编译环境

电商API接口对于实现电商系统平台的搭建有哪些作用?

电商API接口用于实现电商平台的数据交互和功能调用。具体来说&#xff0c;电商API接口可以用于以下几个方面&#xff1a; 1. 商品管理&#xff1a;通过API接口&#xff0c;可以实现商品的添加、修改、删除、查询等操作。商家可以通过API接口将自己的商品信息上传到电商平台&…

C++基础 -22- 菱形继承

理想的菱形继承如图所示 #include "iostream"using namespace std;class top {public:void baseshow(){cout << "baseshow" << endl;} };class left:public::top {public:void leftshow(){cout << "leftshow" << end…

图论|并查集理论基础 1971. 寻找图中是否存在路径

什么是并查集 并查集是一种数据结构&#xff0c;用于处理一些不交集的合并及查询问题。它支持两种操作&#xff1a; 查找&#xff08;Find&#xff09;&#xff1a;确定某个元素属于哪个子集。它可以用来判断两个元素是否属于同一个子集。 合并&#xff08;Union&#xff09;&…

YOLOv8独家原创改进:自研独家创新FT_Conv,卷积高效结合分数阶变换

💡💡💡本文自研创新改进:卷积如何有效地和频域结合,引入分数阶傅里叶变换(FrFT)和分数阶Gabor变换(FrGT),最终创新到YOLOv8。 使用方法:1)直接替换原来的C2f;2)放在backbone SPPF后使用;等 推荐指数:五星 在道路缺陷检测任务中,原始map为0.8,FT_Conv为0.82 收…

力扣题:字符的统计-11.25

力扣题-11.25 [力扣刷题攻略] Re&#xff1a;从零开始的力扣刷题生活 力扣题1&#xff1a;387. 字符串中的第一个唯一字符 解题思想&#xff1a;直接遍历即可 class Solution(object):def firstUniqChar(self, s):""":type s: str:rtype: int""&qu…

【Openstack Train安装】五、Memcached/Etcd安装

本文介绍Memcached/Etcd安装步骤&#xff0c;Memcached/Etcd仅需在控制节点安装。 在按照本教程安装之前&#xff0c;请确保完成以下配置&#xff1a; 【Openstack Train安装】一、虚拟机创建 【Openstack Train安装】二、NTP安装 【Openstack Train安装】三、openstack安装…

插槽slot使用

场景&#xff1a;el-button是绝对定位&#xff0c;希望它能根据query组件&#xff08;公共组件&#xff09;定位&#xff0c;query组件是相对定位。 <query :queryArr"queryParams" class"query"><div class"btn"><el-button cla…

从源代码出发,Jenkins 任务排队时间过长问题的解决过程

最近开发了一个部署相关的工具&#xff0c;使用 Jenkins 来构建应用。Jenkins 的任务从模板中创建而来。每次部署时&#xff0c;通过 Jenkins API 来触发构建任务。在线上运行时发现&#xff0c;通过 API 触发的 Jenkins 任务总是会时不时在队列中等待较长的时间。某些情况下的…

python中的enumerate函数

enumerate函数是Python内置builtins模块中的一个函数&#xff0c;用于将一个可迭代对象转换为一个索引-元素对的枚举对象&#xff0c;从而方便地同时获得索引和元素&#xff0c;并在循环迭代中使用。 enumerate函数的语法格式为&#xff1a;enumerate(iterable, start0) itera…

魔珐科技:3D虚拟人AIGC原生产品,助力全新商业机遇

11月28日-29日&#xff0c;WISE2023 商业之王大会在北京国际会议中心成功举办。此次大会以“太阳照常升起&#xff08;The Sun Always Rises&#xff09;”为主题&#xff0c;活动汇聚了全商业领域知名企业&#xff0c;围绕前沿趋势&#xff0c;共话商业创新之策。 在本次论坛…

ArkTS-警告弹窗

警告弹窗 显示警告弹窗组件&#xff0c;可设置文本内容与响应回调。 使用 Button(点击警告).onClick(()> {AlertDialog.show({title: 标题,message: 内容,autoCancel: true,alignment: DialogAlignment.Center,gridCount: 4,offset: { dx: 0, dy: -20 },primaryButton: {va…

【优选算法系列】【专题十四优先级队列】第一节.(1046. 最后一块石头的重量和703. 数据流中的第 K 大元素)

文章目录 前言一、最后一块石头的重量 1.1 题目描述 1.2 题目解析 1.2.1 算法原理 1.2.2 代码编写 1.2.3 题目总结二、数据流中的第 K 大元素 2.1 题目描述 2.2 题目解析 2.2.1 算法原理 2.2…

v-bind 强制绑定解析表达式, 可以简写v-bind用:冒号

v-bind 指令用于将一个表达式的值动态地绑定到目标元素的属性上。 通过 v-bind&#xff0c;我们可以实现将 Vue 实例的数据或表达式的值绑定到 HTML 属性的功能。 v-bind 可以绑定的属性包括但不限于&#xff1a; HTML 属性&#xff1a;可以绑定常用的 HTML 属性&#xff0c…

无醇啤酒行业分析:预计2028年将达到106亿美元

按照国际惯用的标准划分&#xff0c;通常将酒精度3.5%-4%的称为普通啤酒&#xff0c;将酒精度大于0.5%、小于2.5%的称为低醇啤酒&#xff0c;而酒精度小于0.5%便称为无醇啤酒。酒精给人带来的兴奋感&#xff0c;与体育比赛的紧张刺激相辅相成&#xff0c;啤酒也成为了许多球迷们…

流批一体历史背景及基础介绍

目录 一、历史背景1.BI系统2.传统大数据架构3.流式架构4.Lambda架构5.Kappa架构 二、流批一体与数据架构的关系数据分析型应用数据管道型应用 三、流与批的桥梁Dataflow模型四、Dataflow模型的本质一个基本点两个时间域三个子模型1.窗口模型2.触发器模型3. 增量计算模型 四个分…

Java实现动态加载的逻辑

日常工作中我们经常遇到这样的场景&#xff0c;某某些逻辑特别不稳定&#xff0c;随时根据线上实际情况做调整&#xff0c;比如商品里的评分逻辑&#xff0c;比如规则引擎里的规则。 常见的可选方案有: JDK自带的ScriptEngine 使用groovy&#xff0c;如GroovyClassLoader、Gro…

文生视频的发展史及其原理解析:从Gen2、Emu Video到PixelDance、SVD、Pika 1.0

前言 考虑到文生视频开始爆发&#xff0c;比如11月份就是文生视频最火爆的一个月 11月3日&#xff0c;Runway的Gen-2发布里程碑式更新&#xff0c;支持4K超逼真的清晰度作品(runway是Stable Diffusion最早版本的开发商&#xff0c;Stability AI则开发的SD后续版本)11月16日&a…