一、建立数据库

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项目

添加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类;

输入数据库表名;

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);
} }

查询结果:

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

  1. eclipse生成mybatis的逆向工程-mybatis代码自动生成

    首先,工作中一直在使用命令方式的mybatis的代码自动生成,今天把自己的笔记本直接搞一个在eclipse中生成的逆向代码生成工程,方便自己在家学习使用,在搞这个工程的过程中由于自己搞了一套环境,所i ...

  2. MyBatis代码自动生成(利用命令)

    这几天在学习springmvc,需要用到mybatis,所以研究了一下mybatis自动代码生成,当然也可以手动敲,但是那样效率非常的慢,并且出错率也是很高的,利用MyBatis生成器自动生成实体类. ...

  3. MyBatis代码自动生成

    MyBatis的代码自动生成的功能,由于MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所以可利用MyBatis生成器自动生成实 ...

  4. Spring Boot (七)MyBatis代码自动生成和辅助插件

    一.简介 1.1 MyBatis Generator介绍 MyBatis Generator 是MyBatis 官方出品的一款,用来自动生成MyBatis的 mapper.dao.entity 的框架 ...

  5. Mybatis 代码自动生成[myeclipse版]

    使用环境说明: OS:windows 7 64位 myeclipse: 2017 CI 1.安装 打开myeclipse--help---Install from catalog--选择eclipse ...

  6. Mybatis 代码自动生成(generatorConfig.xml配置)

    博客推荐: Mybatis最入门---代码自动生成(generatorConfig.xml配置) MyBatis Generator generatorConfig.xml配置详解 pom.xml&l ...

  7. mybatis-generator-gui--一个mybatis代码自动生成界面工具

    mybatis-generator-gui是什么 介绍mybatis-generator-gui之前,有必要介绍一下什么是mybatis generator(熟悉的同学可以跳过这一节).我们都知道,通 ...

  8. MyBatis代码自动生成(利用eclipse插件)

    上一篇文章已经介绍了利用命令的方式自动生成mybatis代码,但是每次都去运行cmd命令感觉还是有点麻烦,所以找了些资料发现eclipse里面也可以安装插件自动生成代码,下面简单介绍一下,也是给自己以 ...

  9. Mybatis -代码自动生成(generatorConfig.xml)

    参考:http://blog.csdn.net/jinshiyill/article/details/51546676 官方网址: http://www.mybatis.org/generator/c ...

随机推荐

  1. 入坑java工程师那些事

    最近在知乎上看到好多关于转行做java的朋友,有的在担心学历,有的在想着如何学习java,有的在纠结如何面试.作为一个工作了近10年的java程序员来聊聊我的一些想法,主要从学历.个人能力.工作环境等 ...

  2. Could not get JDBC Connection排查

    最近在维护的一个比较旧的项目,发现总是隔一段时间JDBC就报错: Could not get JDBC Connection; nested exception is org.apache.commo ...

  3. Elasticserch与Elasticsearch_dsl用法

    Elasticserch与Elasticsearch_dsl用法 Elasticsearch_dsl::https://elasticsearch-dsl.readthedocs.io/en/late ...

  4. logstash收集时filebeat区分日志

    logstash收集时filebeat区分日志     1.场景 filebeat在服务器中同时收集nginx和web项目日志,需要对两个日志在logstash中分别处理 2.版本区别 ==6.x之前 ...

  5. typeof的作用及用法

    typeof的作用及用法 1.检查一个变量是否存在,是否有值. typeof在两种情况下会返回"undefined":一个变量没有被声明的时候,和一个变量的值是undefined的 ...

  6. 使用TensorRT集成推理inference

    使用TensorRT集成推理inference 使用TensorRT集成进行推理测试. 使用ResNet50模型对每个GPU进行推理,并对其它模型进行性能比较,最后与其它服务器进行比较测试. ResN ...

  7. Kafka源码分析(三) - Server端 - 消息存储

    系列文章目录 https://zhuanlan.zhihu.com/p/367683572 目录 系列文章目录 一. 业务模型 1.1 概念梳理 1.2 文件分析 1.2.1 数据目录 1.2.2 . ...

  8. 【Azure 机器人】微软Azure Bot 编辑器系列(1) : 创建一个天气对话机器人(The Bot Framework Composer tutorials)

    欢迎来到微软机器人编辑器使用教程,从这里开始,创建一个简单的机器人. 在该系列文章中,每一篇都将通过添加更多的功能来构建机器人.当完成教程中的全部内容后,你将成功的创建一个天气机器人(Weather ...

  9. PTA7~9题目集总结与归纳

    前言: 总结三次题目集的知识点.题量.难度等情况. 目录: 题目集7(7-1).(7-2)两道题目的递进式设计分析总结 题目集8和题目集9两道ATM机仿真题目的设计思路分析总结 一. 题目集7(7-1 ...

  10. 6.11考试总结(NOIP模拟7)

    背景 时间分配与得分成反比,T1 20min 73pts,T2 1h 30pts,T3 2h 15pts(没有更新tot值,本来应该是40pts的,算是本次考试中最遗憾的地方了吧),改起来就是T3比较 ...