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. WebGL学习(3) – 3D模型

    原文地址:WebGL学习(3) – 3D模型 相信很多人是以创建逼真酷炫的三维效果为目标而学习we […]...

  2. App的爬虫—-Appium的使用

    先将Appium的config配置好,再启用   依次将这些数据填写             命令行输入adb […]...

  3. linux root 与普通用户之间的切换

    test@ubuntu:~$ su Password:  root@ubuntu:/home/uu# 也可以是 […]...

  4. 证书pfx转jks

    keytool -importkeystore -srckeystore  2756649_order.han […]...

  5. word中如何设置页码从任意页开始

    一、分开目录与正文 不管你的目录有多少页,首先要做的就是将你的目录与正文分开(作用就如同将目录与正文分别存为两 […]...

  6. 加密算法——RSA算法(c++简单实现)

    RSA算法原理转自:https://www.cnblogs.com/idreamo/p/9411265.htm […]...

  7. 网络协议 1 – 概述

    互联网世界中,网络协议的重要性不言而喻。很多人都知道,网络协议中的五层模型或者七层模型,这些在操作系统中,那都 […]...

  8. java调接口实现发送手机短信验证码功能,手机验证码,接口调用

    java调接口实现发送手机短信验证码功能,手机验证码,接口调用 java调接口实现发送手机短信验证码功能,手机 […]...

展开目录

目录导航