MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1、为什么需要 Mybatis Plus
现在主流的开源 ORM 框架主要是 Mybatis 和 JPA 这两个开源框架,下面我们就来分别看一下这两个开源框架的优势。
1.1 Mybatis 的优势
- SQL 语句可以自由控制,更灵活,性能较高
- SQL 与代码分离,更于阅读和维护
- 提供 XML 标签,支持编写动态 SQL 语句
1.2 JPA 的优势
- JPA 移植性比较好(JPQL),基本不需要修改数据库操作只需要修改数据库配置就可以了
- 提供了很多 CRUD 方法、开发效率高
- 对象化程序更高,数据库表和对应的 JAVA 对应相对应起来,只需要操作对象就可以了
1.3 Mybatis 的劣势
- 简单的 CRUD 操作还得写 SQL 语句
- XML 中有大量的 SQL 要维护
- Mybatis 自身功能很有限,但支持 Plugin
那么又想具有 Mybatis 的的优势, 又想具有 JPA 对象操作的的优势。这个时候,Mybatis Plus 就应运而生了。
2、特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
- 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
3、框架结构
4、Spring Boot 集成 Mybatis Plus
4.1 初始化 SQL
创建一张简单的学生表用于数据库操作。
drop table if exists tb_student;
create table tb_student
(
id bigint unsigned auto_increment comment '主键',
username varchar(64) comment '请求号',
address varchar(64) comment '商户号',
create_time datetime comment '创建时间',
update_time datetime comment '修改时间',
primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET utf8;
insert into tb_student(username, address, create_time, update_time) values ('zhangsan', 'xxxxxx', now(), now());
insert into tb_student(username, address, create_time, update_time) values ('lisi', 'yyyyyy', now(), now());
4.2 maven 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.carlzone.test</groupId>
<artifactId>fintech-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fintech-test</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
</dependencies>
<build>
<finalName>fintech-notice-client</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4.3 spring boot 配置文件
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
spring.datasource.username=carl
spring.datasource.password=123456
4.4 Student.java
@Data
@Accessors(chain = true)
@TableName("tb_student")
public class Student {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("username")
private String username;
@TableField("address")
private String address;
@TableField("create_time")
private Date createTime;
@TableField("update_time")
private Date updateTime;
}
4.5 StudentMapper.java
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
4.6 StudentDao.java
public interface StudentDao extends IService<Student> {
int deleteStudentById(Long id);
int updateAddressById(String address, Long id);
int saveStudent(Student student);
Student findStudentById(Long id);
List<Student> findStudentsByCreateTime(Date crateTime);
List<Student> findAllStudent();
}
4.7 StudentDaoImpl.java
@Repository(value = "studentDao")
public class StudentDaoImpl extends ServiceImpl<StudentMapper, Student> implements StudentDao {
@Resource
private StudentMapper mapper;
@Override
public int deleteStudentById(Long id) {
return mapper.deleteById(id);
}
@Override
public int updateAddressById(String address, Long id) {
return mapper.update(new Student().setAddress(address).setUpdateTime(new Date()),
new UpdateWrapper<Student>().eq("id", id));
}
@Override
public int saveStudent(Student student) {
return mapper.insert(student);
}
@Override
public Student findStudentById(Long id) {
return mapper.selectById(id);
}
@Override
public List<Student> findStudentsByCreateTime(Date crateTime) {
return super.list(new QueryWrapper<Student>().le("create_time", crateTime));
}
@Override
public List<Student> findAllStudent() {
return super.list();
}
}
4.8 测试 Controller
@RestController
@RequestMapping("student")
public class StudentController {
@Resource(name = "studentDao")
private StudentDao studentDao;
@RequestMapping("all")
public Map<String, Object> students(){
Map<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("message", "success");
result.put("data", studentDao.findAllStudent());
return result;
}
@RequestMapping("address")
public Map<String, Object> address(String address, Long id) {
studentDao.updateAddressById(address, id);
Map<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("message", "success");
return result;
}
}
5、测试
5.1 查询所有的学生
5.2 修改张三的地址
5.3 再次查询所有的学生
此时张三的地址已经更新了