mybatisplus代码生成器_想做时间管理大师?你可以试试Mybatis Plus代码生成器

88d2c422a2bccb0b01f7e4f2d56f2453.png

1. 前言

对于写Crud的老司机来说时间非常宝贵,一些样板代码写不但费时费力,而且枯燥无味。经常有小伙伴问我,胖哥你怎么天天那么有时间去搞新东西,透露一下秘诀呗。

135b38efb604a948fdcbc3cb2e8c8d2f.png

好吧,今天就把Mybatis-plus的代码生成器分享出来,让你也成为一个优秀的时间管理大师。

2. 基本依赖

Spring BootMySQL为例,你需要下面这些依赖:

    org.projectlombok    lombok    compile    com.zaxxer    HikariCP    mysql    mysql-connector-java    com.baomidou    mybatis-plus-boot-starter    com.baomidou    mybatis-plus-generator    compile    true    org.springframework.boot    spring-boot-starter-freemarker    compile    true

然后配置好你的数据库,确保数据库连接通讯畅通。

3. 定制代码生成器

这里我期望生成的目录结构是这样的:

23b633eb965cf32eab8ba2f2a48ba33a.png

于是我花了点时间定制了一些生成器的配置,代码如下,就是这么硬核!

package cn.felord.mybatis.util;​import com.baomidou.mybatisplus.annotation.DbType;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.core.toolkit.StringPool;import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.InjectionConfig;import com.baomidou.mybatisplus.generator.config.*;import com.baomidou.mybatisplus.generator.config.po.TableInfo;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;​import java.util.ArrayList;import java.util.List;import java.util.Optional;​​/** * 代码生成器配置 * * @author felord * @since 10 :39  2018/9/9 */public class CodeGenerator {    private String dbUrl;    private String userName;    private String password;    private String dir;    private String xmlDir;    private String packageName;​    private CodeGenerator() {    }​    /**     * The type Config builder.     */    public static class ConfigBuilder {​        private String dbUrl;        private String userName;        private String password;        private String dir;        private String xmlDir;        private String packageName;​​        /**         * Db url config builder.         *         * @param dbUrl the db url         * @return the config builder         */        public ConfigBuilder dbUrl(final String dbUrl) {            this.dbUrl = dbUrl;            return this;        }​        /**         * User name config builder.         *         * @param userName the user name         * @return the config builder         */        public ConfigBuilder userName(final String userName) {            this.userName = userName;            return this;        }​        /**         * Password config builder.         *         * @param password the password         * @return the config builder         */        public ConfigBuilder password(final String password) {            this.password = password;            return this;        }​        /**         * Dir config builder.         *         * @param dir the dir         * @return the config builder         */        public ConfigBuilder dir(final String dir) {            this.dir = dir;            return this;        }​        /**         * Dir config builder.         *         * @param xmlDir the dir         * @return the config builder         */        public ConfigBuilder xmlDir(final String xmlDir) {            this.xmlDir = xmlDir;            return this;        }​        /**         * Package name config builder.         *         * @param packageName the package name         * @return the config builder         */        public ConfigBuilder packageName(final String packageName) {            this.packageName = packageName;            return this;        }​        /**         * Build code generator.         *         * @return the code generator         */        public CodeGenerator build() {            CodeGenerator generator = new CodeGenerator();​            generator.dbUrl = Optional.of(this.dbUrl).get();            generator.userName = Optional.of(this.userName).get();            generator.password = Optional.of(this.password).get();            generator.dir = Optional.of(this.dir).get();            generator.xmlDir = Optional.of(this.xmlDir).get();            generator.packageName = Optional.of(this.packageName).get();            return generator;        }    }​​    /**     * Code.     *     * @param tableNames the table names     */    public void code(String... tableNames) {        codingMysql(true, false, true, this.dbUrl, this.userName, this.password, this.dir, this.xmlDir, this.packageName, tableNames);    }​    /**     *     * 生成器核心部分     *     * @param serviceNameStartWithI 是否前缀I     * @param createController      是否生成controller     * @param useLombok             是否使用 lombok     * @param dbUrl                 数据库连接     * @param username              用户名称     * @param password              密码     * @param outDir                输出目录     * @param xmlDir                xml 文件目录     * @param packageName           包路径     * @param tableNames            表名称     */    private static void codingMysql(boolean serviceNameStartWithI,                                    boolean createController,                                    boolean useLombok,                                    String dbUrl,                                    String username,                                    String password,                                    String outDir,                                    String xmlDir,                                    String packageName,                                    String... tableNames) {        GlobalConfig config = new GlobalConfig();        DataSourceConfig dataSourceConfig = new DataSourceConfig();//        数据库类型 这里使用 mysql        dataSourceConfig.setDbType(DbType.MYSQL)                .setUrl(dbUrl)                .setUsername(username)                .setPassword(password)//                驱动名称  这里使用mysql                .setDriverName("com.mysql.jdbc.Driver");​        // 自定义xml输出路径        InjectionConfig cfg = new InjectionConfig() {            @Override            public void initMap() {                // to do nothing            }        };        List focList = new ArrayList<>();//        你也可以定制 xml 的模板        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {            @Override            public String outputFile(TableInfo tableInfo) {                // 自定义xml文件的路径                return xmlDir + "/mapper/" + tableInfo.getMapperName() + StringPool.DOT_XML;            }        });        cfg.setFileOutConfigList(focList);​​//        策略配置项        StrategyConfig strategyConfig = new StrategyConfig();        strategyConfig                .setCapitalMode(false)//                是否使用 lombok                .setEntityLombokModel(useLombok)//                下划线转驼峰                .setNaming(NamingStrategy.underline_to_camel)                //修改替换成你需要的表名,多个表名传数组                .setInclude(tableNames);//        使用 AR 模式        config.setActiveRecord(true)//                设置头注释的 author                .setAuthor("system")//                项目输出路径                .setOutputDir(outDir)//                是否覆盖已经生成的同名文件                .setFileOverride(true)//                雪花算法生成id                .setIdType(IdType.ASSIGN_ID)//                是否使用缓存                .setEnableCache(false)//                是否生成 xml 中的 基础 resultMap                .setBaseResultMap(true);        if (!serviceNameStartWithI) {//            Service 层的 通用格式后缀            config.setServiceName("%sService");        }//             实体类包名        PackageConfig packageConfig = new PackageConfig().setParent(packageName).setEntity("entity");        TemplateConfig templateConfig = new TemplateConfig().setXml(null);//        这里选择不生成 controller  实际上 生成的大多不符合我们需要  到服务层就行了        if (!createController) {            templateConfig.setController(null);        }//        整合起来运行        new AutoGenerator()                .setGlobalConfig(config)                .setTemplateEngine(new FreemarkerTemplateEngine())                .setDataSource(dataSourceConfig)                .setStrategy(strategyConfig)                .setPackageInfo(packageConfig)                .setCfg(cfg)                .setTemplate(templateConfig)                .execute();    }​}​

如果我生成的目录结构能够满足你的需要,那就巧了,直接拿去用;如果不满足需要,你可以按照注释的说明进行微调。18年搞的用了好几年,没出过什么乱子。

4. 代码生成器的使用

使用起来非常简单,确保数据库能够使用JDBC连接成功,写个main方法,配置一下,跑起来就是了:

/** * @author felord.cn * @since 11:34 **/public class AutoCoding {    public static void main(String[] args) {​//          maven 工程 main 包的全路径        final String mainDir = "C:IdeaProjectsbc-recylingsrcmain";​        CodeGenerator.ConfigBuilder builder = new CodeGenerator.ConfigBuilder();​        CodeGenerator codeGenerator = builder//                数据库连接                .dbUrl("jdbc:mysql://localhost:3306/test")//                账户                .userName("root")//                密码                .password("123456")                // 生成类位置                .dir(mainDir + "java")                // 生成xml 位置                .xmlDir(mainDir + "resources")                // 包引用路径                .packageName("cn.felord.mybatis")                .build();​        //根据表生成后台代码        codeGenerator.code("user_info");​​    }}

然后代码就生成了,是不是非常的好用?恭喜你获得了 时间管理大师 荣誉称号。

切记不要炫耀,否则需求加倍。

5. 总结

虽然好用,但是建议新手不要使用,多手写一下代码。另外复杂的SQL还是建议自己写,多锻炼写SQL的能力。如果你在使用中有什么问题,可以私信我进行沟通。如果你有更加好用的可以通过留言分享给广大条友。

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

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

相关文章

安装Oracle 11g RAC R2 之Linux DNS 配置

Oracle 11g RAC 集群中引入了SCAN(Single Client Access Name)的概念&#xff0c;也就是指集群的单客户端访问名称。SCAN 这个特性为客户端提供了单一的主机名&#xff0c;用于访问集群中运行的 Oracle 数据库。如果您在集群中添加或删除节点&#xff0c;使用 SCAN 的客户端无需…

c++ websocket客户端_websocket使用

websocket使用一、介绍在项目开发过程中&#xff0c;很多时候&#xff0c;我们不可避免的需要实现的一个功能&#xff1a; 服务端实时发送信息给客户端。比如实时公告、实时订单通知、实时报警推送等等&#xff0c;登录后的客户端需要知道与它相关的实时信息&#xff0c;以便进…

汉子编码比字母编码长_字母/博客作者编码问题(使用动态编程)

汉子编码比字母编码长Problem statement: 问题陈述&#xff1a; Shivang is a blog writer and he is working on two websites simultaneously. He has to write two types of blogs which are: Shivang是一位博客作家&#xff0c;他同时在两个网站上工作。 他必须写两种类型…

php parent报错,mac brew 安装php扩展报错:parent directory is world writable but not sticky

$ brew install php70-mcrypt报错&#xff1a;Error: parent directory is world writable but not sticky搜索到github的答案https://github.com/Homebrew/legacy-homebrew/issues/40345原因&#xff1a;/tmp目录权限不对$ ls -ld /private/tmp打印出来 /private/tmp 被标黄了…

在cordova中使用HTML5的多文件上传

2019独角兽企业重金招聘Python工程师标准>>> 我们先看看linkface给开放的接口&#xff1a; 字段类型必需描述api_idstring是API 账户api_secretstring是API 密钥selfie_filefile见下方注释需上传的图片文件 1&#xff0c;上传本地图片进行检测时选取此参数selfie_ur…

python dataframe切片_python pandas dataframe 行列选择,切片操作方法

SQL中的select是根据列的名称来选取&#xff1b;Pandas则更为灵活&#xff0c;不但可根据列名称选取&#xff0c;还可以根据列所在的position&#xff08;数字&#xff0c;在第几行第几列&#xff0c;注意pandas行列的position是从0开始&#xff09;选取。相关函数如下&#xf…

php根据设备判断访问,PHP判断设备访问来源

/*** 判断用户请求设备是否是移动设备* return bool*/function isMobile() {//如果有HTTP_X_WAP_PROFILE则一定是移动设备if (isset($_SERVER[HTTP_X_WAP_PROFILE])) {return true;}//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息if (isset($_SERVER[HTTP_VIA])…

机器学习 深度学习 ai_如何学习机器学习和人工智能?

机器学习 深度学习 aiSTRATEGY 战略 Learn theory practical aspects. 学习理论和实践方面的知识。 (At first get an overview of what you are going to learn). (首先获得要学习的内容的概述)。 Gain a good hold/insight on each concept. 掌握/理解每个概念。 If you …

linux常用命令和配置

2019独角兽企业重金招聘Python工程师标准>>> 启动php&#xff1a; /etc/init.d/php-fpm restart 查看PHP运行目录&#xff1a; which php /usr/bin/php 查看php-fpm进程数&#xff1a; ps aux | grep -c php-fpm 查看运行内存 /usr/bin/php -i|grep mem iptables如…

centos7时间同步_centos 8.x系统配置chrony时间同步服务

centos 8.x系统配置chrony时间同步服务CentOS 7.x默认使用的时间同步服务为ntp服务&#xff0c;但是CentOS 8开始在官方的仓库中移除了ntp软件&#xff0c;换成默认的chrony进行时间同步的服务&#xff0c;chrony既可以作为客户端向其他时间服务器发送时间同步请求&#xff0c;…

php可以用scanf,C/C++中 使用scanf和printf如何读入输出double型数据。

黄舟2017-04-17 13:47:232楼注意scanf函数和printf函数是不同寻常的函数&#xff0c;因为它们都没有将函数的参数限制为固定数量。scanf函数和printf函数又可变长度的参数列表。当调用带可变长度参数列表的函数时&#xff0c;编译器会安排float参数自动转换成为double类型&…

ICWAI和ICWA的完整形式是什么?

ICWAI / ICWA&#xff1a;印度成本与工程会计师协会/印度儿童福利法 (ICWAI / ICWA: Institute of Cost and Works Accountants of India / Indian Child Welfare Act) 1)ICWAI&#xff1a;印度成本与工程会计师协会 (1) ICWAI: Institute of Cost and Works Accountants of In…

深入研究java.lang.Runtime类【转】

转自&#xff1a;http://blog.csdn.net/lastsweetop/article/details/3961911 目录(?)[-] javalang 类 RuntimegetRuntimeexitaddShutdownHookremoveShutdownHookhaltrunFinalizersOnExitexecexecexecexecexecexecavailableProcessorsfreeMemorytotalMemorymaxMemorygcrunFina…

java队列实现限流,java中应对高并发的两种策略

目的&#xff1a;提高可用性通过ExecutorService实现队列泄洪//含有20个线程的线程池private ExecutorService executorService Executors.newFixedThreadPool(20);将有并发压力的下游代码放入到线程池的submit方法中&#xff0c;如下&#xff1a;//同步调用线程池的submit方法…

crontab 日志_liunx 中定时清理过期日志文件

问题描述经常遇到日志文件过多&#xff0c;占用大量磁盘空间&#xff0c;需要定期删除过期日志。问题涉及方面删除过期日志的脚本。定时任务删除任务脚本先查询到过期的日志文件&#xff0c;然后删除。语法find path -option [ -print ] [ -exec -ok command ] …

JavaScript | 数组的常用属性和方法

JavaScript的通用属性和数组方法 (Common properties and methods of array in JavaScript ) Properties/MethodsDescriptionsarray.lengthReturns the length of the array/total number of elements of the array array[index]Returns the item name stored at “index” pos…

php dbutils 使用,dbutilsapi

相对lisp?而?言,可以使?用.net的强?大api,实现各种酷炫功能。相对c#及arx?...文件utils.py的模块名分别是mycompany.utils和 mycompany.web.utils。 mycompany......CouchDB -b 关闭后台运行的 CouchDB : CouchDB -d web 访问:http://127.0.0.1:5984/_utils/index.html E-…

html 导航栏

<!DOCTYPE html> <html> <head> <meta charset"utf-8"> <title>lvnian学习(http://lvnian.blog.51cto.com/)</title> <style> ul {list-style-type:none;margin:0;padding:0; }a:link,a:visited{display:block;font-weigh…

将搜索二叉树转换为链表_将给定的二叉树转换为双链表(DLL)

将搜索二叉树转换为链表Given a Binary tree and we have to convert it to a Doubly Linked List (DLL). 给定二叉树&#xff0c;我们必须将其转换为双链表(DLL)。 Algorithm: 算法&#xff1a; To solve the problem we can follow this algorithm: 为了解决这个问题&#…

cuda编程_CUDA刷新器:CUDA编程模型

CUDA刷新器&#xff1a;CUDA编程模型 CUDA Refresher: The CUDA Programming Model CUDA&#xff0c;CUDA刷新器&#xff0c;并行编程 这是CUDA更新系列的第四篇文章&#xff0c;它的目标是刷新CUDA中的关键概念、工具和初级或中级开发人员的优化。 CUDA编程模型提供了GPU体系结…