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. 内置函数

    内置函数 数值型函数 abs(x) 功能 返回x的绝对值 参数 x数值型 返回 数字 select abs(1 […]...

  2. 在Linux上使用的10种云备份方案

    在Linux上使用的10种云备份方案 导读 不久前,为用户提供一种备份远程机器上数据的简易方法还很稀奇。现在, […]...

  3. 一个commit引发的思考

    这几天我翻了翻golang的提交记录,发现了一条很有意思的提交:bc593ea,这个提交看似简单,但是引人深思 […]...

  4. 基于keras-yolo3,原理及代码细节的理解

    基于keras-yolo3,原理及代码细节的理解 Posted on 2018-10-31 16:35 香菇肥 […]...

  5. HTML5 Canvas

    HTML5 Canvas Canvas ,HTML 5中引入它,可以做很多事情:画图、动画、游戏开发等等。本篇 […]...

  6. windows下如何制作和应用数字签名证书 全流程

    目前我们在发布应用程序时,有时用户下载后会被360杀毒当做木马直接隔离。为应用程序可执行文件打上数字签名可以让 […]...

  7. 【docker Elasticsearch】Rest风格的分布式开源搜索和分析引擎Elasticsearch初体验

    概述: Elasticsearch 是一个分布式、可扩展、实时的搜索与数据分析引擎。 它能从项目一开始就赋予你 […]...

  8. MySQL中的insert ignore into, replace into等的一些用法总结 – bijian1013

    MySQL中的insert ignore into, replace into等的一些用法总结 mysql中常 […]...

展开目录

目录导航