1、介绍

Mybatis
Mybatis 是操作数据库的框架:提供一种Mapper类,支持用Java代码对数据库进行增删改查。

缺点:需要先在xml中写好SQL语句;
Mybatis Generator
自动为Mybatis生成简单的增删改查SQL语句的工具
Mybatis-Plus
MyBatis-Plus 是一个Mybatis 增强版工具,在 MyBatis 基础上扩充了功能(由国人团队苞米豆开发)。
作用:为了简化开发效率。
Mybatis Plus Generator
比Mybatis Generator更加强大,支持功能更多,可自动生成:
Entity、Mapper、Service、Controller等

2、Mybatis Plus Generator用法演示

2.1、工程创建与依赖配置

通过IDEA新建Spring工程,在工程的pom.xml文件中配置依赖:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!--mp-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!--模板-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mp代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
2.2、数据库构建与项目配置

使用Navicat创建mysql数据库 “vueblog”,创建数据表,SQL语句(自己懒得写,参考某大神的现成的SQL):

CREATE TABLE `m_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(64) DEFAULT NULL,
`avatar` varchar(255) DEFAULT NULL,
`email` varchar(64) DEFAULT NULL,
`password` varchar(64) DEFAULT NULL,
`status` int(5) NOT NULL,
`created` datetime DEFAULT NULL,
`last_login` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `UK_USERNAME` (`username`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `m_blog` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL,
`title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`content` longtext,
`created` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
`status` tinyint(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4; INSERT INTO `vueblog`.`m_user` (`id`, `username`, `avatar`, `email`, `password`, `status`, `created`, `last_login`) VALUES ('1', 'test', 'https://image-1300566513.cos.ap-guangzhou.myqcloud.com/upload/images/5a9f48118166308daba8b6da7e466aab.jpg', NULL, '96e79218965eb72c92a549dd5a330112', '0', '2020-04-20 10:44:01', NULL);

在工程的application.properties中,配置数据源datasource与mybatis-plus:

server.port=8080

# DataSource Config
spring.datasource.url=jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=qixingchao
spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis-plus.mapper-locations=classpath*:/mapper/**Mapper.xml
2.3、导入、调整CodeGenerator源码

注意:数据源、包名信息一定要根据自己项目信息进行调整

package com.qxc;

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.setAuthor("qixingchao");
gc.setOpen(false);
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc); // 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("qixingchao");
mpg.setDataSource(dsc); // 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent("com.qxc");
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();
}
}
2.4 执行CodeGenerator

右键CodeGenerator.java类 --> 选择"Run 'CodeGenerator.main()' "

IDEA底部弹出输入面板,手动输入数据库表名:

回车,自动生成基础代码:

2.5 代码测试

工程Application类增加自动扫描代码MapperScan:

package com.qxc;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("com.qxc.mapper")
public class VueblogApplication {
public static void main(String[] args) {
SpringApplication.run(VueblogApplication.class, args);
}
}

UserController类里写接口测试方法:

package com.qxc.controller;

import com.qxc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /**
* <p>
* 前端控制器
* </p>
*
* @author qixingchao
* @since 2021-04-12
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService; @GetMapping("/{id}")
public Object getUserById(@PathVariable("id")long id){
return userService.getById(id);
}
}

通过IDEA启动工程,在浏览器输入与接口匹配的URL地址:

Mybatis、Mybatis Generator、Mybatis-Plus、Mybatis Plus Generator的更多相关文章

  1. 使用MyBatis Generator自动生成实体、mapper和dao层

    原文链接 通过MyBatis Generator可以自动生成实体.mapper和dao层,记录一下怎么用的. 主要步骤: 关于mybatis从数据库反向生成实体.DAO.mapper: 参考文章:ht ...

  2. MyBatis学习4---使用MyBatis_Generator生成Dto、Dao、Mapping

    由于MyBatis属于一种半自动的ORM框架,所以主要的工作将是书写Mapping映射文件,但是由于手写映射文件很容易出错,所以查资料发现有现成的工具可以自动生成底层模型类.Dao接口类甚至Mappi ...

  3. MyBatis之四:调用存储过程含分页、输入输出参数

    在前面分别讲解了通过mybatis执行简单的增删改,多表联合查询,那么自然不能缺少存储过程调用,而且还带分页功能. 注意:表结构参见上篇讲解联合查询的表. 一.查询某班级以及该班级下面所有学生的记录 ...

  4. Mybatis中实现oracle的批量插入、更新

    oracle 实现在Mybatis中批量插入,下面测试可以使用,在批量插入中不能使用insert 标签,只能使用select标签进行批量插入,否则会提示错误 ### Cause: java.sql.S ...

  5. mybatis 详解(七)------一对一、一对多、多对多

    前面几篇博客我们用mybatis能对单表进行增删改查操作了,也能用动态SQL书写比较复杂的sql语句.但是在实际开发中,我们做项目不可能只是单表操作,往往会涉及到多张表之间的关联操作.那么我们如何用 ...

  6. Mybatis第八篇【一级缓存、二级缓存、与ehcache整合】

    Mybatis缓存 缓存的意义 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题. myba ...

  7. Mybatis第六篇【配置文件和映射文件再解读、占位符、主键生成与获取、Mapper代理】

    配置文件和映射文件再解读 映射文件 在mapper.xml文件中配置很多的sql语句,执行每个sql语句时,封装为MappedStatement对象,mapper.xml以statement为单位管理 ...

  8. JAVAEE——Mybatis第一天:入门、jdbc存在的问题、架构介绍、入门程序、Dao的开发方法、接口的动态代理方式、SqlMapConfig.xml文件说明

    1. 学习计划 第一天: 1.Mybatis的介绍 2.Mybatis的入门 a) 使用jdbc操作数据库存在的问题 b) Mybatis的架构 c) Mybatis的入门程序 3.Dao的开发方法 ...

  9. SpringBoot整合Mybatis完整详细版二:注册、登录、拦截器配置

    接着上个章节来,上章节搭建好框架,并且测试也在页面取到数据.接下来实现web端,实现前后端交互,在前台进行注册登录以及后端拦截器配置.实现简单的未登录拦截跳转到登录页面 上一节传送门:SpringBo ...

  10. Mybatis框架三:DAO层开发、Mapper动态代理开发

    这里是最基本的搭建:http://www.cnblogs.com/xuyiqing/p/8600888.html 接下来做到了简单的增删改查:http://www.cnblogs.com/xuyiqi ...

随机推荐

  1. Windows 官方提供的触屏硬件延迟测量方法

    本文记录微软 Windows 官方在 Windows Hardware Lab Kit 提供的触屏硬件延迟测量方法 Overview of measuring Touch Down Hardware ...

  2. WPF 已知问题 Popup 失焦后导致 ListBox 无法用 MouseWheel 滚动问题和解决方法

    本文记录在 Popup 失焦后导致 ListBox 无法用 MouseWheel 滚动问题 原因: Popup虽然是个完整独立的窗体,但它的激活要靠它的"父窗口"间接来激活,这里之 ...

  3. dotnet C# 基础 为什么 GetHashCode 推荐只取只读属性或字段做哈希值

    在 C# 里面,所有的对象都继承 Object 类型,此类型有开放 GetHashCode 用于给开发者重写.此 GetHashCode 方法推荐是在重写 Equals 方法时也同时进行重写,要求两个 ...

  4. 万字长文总结与剖析C语言关键字 -- <<C语言深度解剖>>

    C总结与剖析:关键字篇 -- <<C语言深度解剖>> 目录 C总结与剖析:关键字篇 -- <<C语言深度解剖>> 程序的本质:二进制文件 变量 1.变量 ...

  5. 4.k8s-配置网络策略 NetworkPolicy

    一.基本了解 官方文档:https://kubernetes.io/zh-cn/docs/concepts/services-networking/network-policies/基本了解: 1.网 ...

  6. EFK+logstash构建日志收集平台

    一.环境 k8s集群: 控制节点:192.168.199.131  主机名:master  配置:4核6G 工作节点:192.168.199.128  主机名:monitor 配置:4核4G 1.1 ...

  7. vue-cli快速搭建项目的几个文件(二)

    =======ggcss样式======== :root{     --bgColor : #d3252a;     --pinkColor : #ff4e81;     --textColor :  ...

  8. 游戏陪玩公众号H5软件开发方案图文详解

    用户需求 无论开发怎样的产品,都需要事先对整个市场行情和用户需求进行简单的了解.前面的一组数据已经简明扼要的摆明了现在陪玩市场的行情.而现如今,大多数游戏都需要组队进行,如英雄联盟.王者荣耀.绝地求生 ...

  9. 应急响应--windows入侵排查

  10. FE宝典

    前端学科面试宝典 蔡威 [电子邮件地址] HTML5.CSS3..................................................................... ...