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 再次查詢所有的學生
此時張三的地址已經更新了