Mybatis代码自动生成(含测试)

1908834224cxm 2021-07-14 原文


Mybatis代码自动生成(含测试)


一、建立数据库

create database shixun;
use shixun;
create table user(
    id int primary key auto_increment ,
    username varchar(50) not null,
    password varchar(50) not null,
    phone varchar(11),
    email varchar(25),
    sex varchar(3),
    age int,
    address varchar(50)
);
insert into user(id,username,password,phone,email,sex,age,address)
values (1,'admin1','12345','183','1908834224@qq.com','女',18,'重庆');
insert into user(id,username,password,phone,email,sex,age,address)
values (2,'admin2','12345','183','1908834224@qq.com','男',18,'重庆');

二、新建SpringBoot项目

0af937bf71a641786267a6ce527e6316.png

添加pom.xml依赖:

        <!--代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-commons</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

编写代码自动生成类

package com.cxm.demo;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.Scanner;

public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        // gc.setOutputDir("D:\\test");
        gc.setAuthor("DaiDaiMei");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        gc.setServiceName("%sService");
        mpg.setGlobalConfig(gc);

        // 数据源配置 数据库名 账号密码
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("3642");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent("com.cxm.demo");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!
                return projectPath + "/src/main/resources/mapper/"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        //strategy.setTablePrefix("m_");//去掉表的前缀
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

只需修改:

  • 作者信息

     gc.setAuthor("DaiDaiMei");
    
  • 包路径

     pc.setParent("com.cxm.demo");
    
  • 数据库信息

     DataSourceConfig dsc = new DataSourceConfig();
     dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
     // dsc.setSchemaName("public");
     dsc.setDriverName("com.mysql.cj.jdbc.Driver");
     dsc.setUsername("root");
     dsc.setPassword("1111");
     mpg.setDataSource(dsc);
    

运行CodeGenerator类;

输入数据库表名;

860d40c07de13beaacfbfba73881123a.png

enter后就会自动生成controller、mapper、entity、service啦。

编写resource里的properties文件

mybatis-plus.mapper-locations=classpath*:/mapper/**Mapper.xml
server.port=8081
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.password=1111
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
spring.datasource.username=root

修改数据库信息就可以了。

三、测试

在DemoApplication里添加注解:

@MapperScan("com.cxm.demo.mapper")

定义变量:

@Resource
private UserMapper userMapper;

测试查询所有信息

@Test
public void TestSelect(){

    QueryWrapper<User> qw = new QueryWrapper<>();

    List<User> list = userMapper.selectList(qw);

    for (User user1 : list) {
        System.out.println(user1);
    }
        
}

查询结果:

34c02d94f30b65bc73e4fe0e92106207.md.png

发表于
2021-07-14 10:05 
呆呆槑 
阅读(0
评论(0
编辑 
收藏 
举报

 

版权声明:本文为1908834224cxm原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/1908834224cxm/p/15009539.html

Mybatis代码自动生成(含测试)的更多相关文章

随机推荐

  1. 如何让路由自动获取公网的IP

    前段时间抓一个网站的数据,呵呵,这个网站就不说了,反正也是蛮出名的一家公司,然后数据还是挺干净的,呵呵,我让抓 […]...

  2. 列表生成式

    今天在复习列表运算的时候,一直纳闷python为什么对列表元素操作这么麻烦,无意间看到“列表生成式”,居然发现 […]...

  3. 【xingorg1-ui】基于vue3.0从0-1搭建组件库(一)环境配置与目录规划

    【xingorg1-ui】基于vue3.0从0-1搭建组件库 npm地址 github源码 开篇-环境配置 环 […]...

  4. fpga pll重配置实验总结

    今天做了pll重配置的实验,输入时钟50m初始配置输出75m经重配置后输出100m,带宽为low,使用的ip: […]...

  5. 【免费分享】帝国CMS7.5仿《优优健康网》整站源码/带独立移动端手机版模板+数据采集

    本资源可免费获取,请至尾部读阅! 帝国CMS7.5仿《优优健康网》网站模板,7.2版本修复升级7.5版本,带独 […]...

  6. SuperEdge 易学易用系列-SuperEdge 简介

    关于 SuperEdge SuperEdge 是由腾讯、Intel、VMware、虎牙直播、寒武纪、首都在线和 […]...

  7. centos 6.2(x86_64) 下eclim 安装记录

    eclim官网:http://eclim.org/ 按照官网的步骤下载并安装好eclipse,注意看下ecli […]...

  8. 推荐5款自学手机APP,请低调收藏,让你变得越来越优秀

    现在的手机APP真的是太多了,但里面的功能同类性又非常大,很难找到实用并且符合要求的APP。接下来就为小伙伴们 […]...

展开目录

目录导航