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. WPF 触摸下如何给 StylusPointCollection 添加点

    本文告诉大家如何在触摸下给 WPF 的 StylusPointCollection 添加新的点 在自己默认创建的 StylusPointCollection 里面添加点是十分简单的,如以下代码,可以非 ...

  2. VisualStudio 禁用移动文件到文件夹自动修改命名空间功能

    在 VisualStudio 2022 里的某个版本开始,将会在移动文件到其他文件夹时,自动修改命名空间,使用匹配文件夹路径的命名空间.如果这个功能能顺手将其他引用此类型的全部符号同时变更,那自然是很 ...

  3. Apache Pulsar 桌面端图形化管理工具

    Apache Pulsar 桌面端图形化管理工具 Apache Pulsar 是 Apache 软件基金会顶级项目,是下一代云原生分布式消息流平台,集消息.存储.轻量化函数式计算为一体,采用计算与存储 ...

  4. 11.Node节点维护

    题目:Node节点维护 配置环境kubectl config use-context ek8s 将名为ek8s-node-0的node节点设置为不可用,并重新调度该node上所有运行的pods. 官方 ...

  5. Google高精度的搜索技巧

    利用"关键字",完全匹配搜索(双引号精准搜索). 利用"关键字:档案类型",搜寻特定档案类型. 例如:"简历:doc"."钢铁侠: ...

  6. 深入理解 C++ 中的多态与文件操作

    C++ 多态 多态(Polymorphism)是面向对象编程(OOP)的核心概念之一,它允许对象在相同操作下表现出不同的行为.在 C++ 中,多态通常通过继承和虚函数来实现. 理解多态 想象一个场景, ...

  7. 微分流形Loring Tu 习题21.2解答

    今天的作业,随手写到博客吧. \(Proof.\)对于任意的\(p \in M\),有p附近的坐标卡\((U,x^{1},\ldots,x^{n})\), 由引理\(21.4\),$$dx^{1}\w ...

  8. 02、Linux 排查

    Linux 分析排查 1.敏感文件信息 1.1.tmp 目录 /tmp:临时目录文件,每个用户都可以对它进行读写操作.因此一个普通用户可以对 /tmp 目录执行读写操作(ls -alt) 筛查 /tm ...

  9. 轻量级.net standard微信支付登录Nuget开源库

    我个人编写的库,在我个人网站,小程序等很多地方都在使用中,大家可以搜索小程序 什邡市宅猫君网络工作室 或者到我的网站 store.zhaimaojun.cn 去体验支付和登录效果. 本库主要实现了na ...

  10. juc之ConcurrentHashMap在我工作中的实践

    Map是我工作中应用比较多的数据结构之一,主要用来存储一些kv的映射信息,如果是单线程环境下我会优先使用HashMap,但是如果在多线程环境下继续使用HashMap我不确定会不会被我老大打死,为了生命 ...