1 Mybatis-Plus简介
1.1 什么是Mybatis-Plus
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1.2 为什么要学习Mybatis-Plus
我们已经学习过Mybatis这个框架,我们只需要在dao层定义抽象接口,基于Mybatis零实现的特性,就可以实现对数据库的crud操作。在业务类型比较多的时候,我们需要重复的定义一堆功能类似的接口方法。
使用Mybatis-plus工具,我们只需要将我们定义的抽象接口,继承一个公用的 BaseMapper 接口,就可以获得一组通用的crud方法,来操作数据库。使用Mybatis-plus时,甚至都不需要任何的xml映射文件或者接口方法注解,真正的dao层零实现。
2 入门示例
2.1 需求
使用Mybatis-Plus实现对用户的crud操作。
2.2 配置步骤说明搭建环境(创建项目、导入包)
配置Mybaits-Plus(基于Spring实现)
编写测试代码
2.3 配置步骤
2.3.1 第一步:搭建环境
2.3.1.1 数据库准备
CREATE TABLE `tb_user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
)
2.3.1.2 说明Mybatis-Plus并没有提供单独的jar包,而是通过Maven(或者gradle)来管理jar依赖。
Mybatis-Plus是基于Spring框架实现的,因此使用Mybatis-Plus,必须导入Spring相关依赖。
2.3.1.3 添加依赖
编写 pom 配置文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.oza.mybatisplus
mybatisplus-demo-start
1.0-SNAPSHOT
com.baomidou
mybatis-plus
3.1.2
org.springframework
spring-context
4.3.2.RELEASE
org.springframework
spring-jdbc
4.3.2.RELEASE
org.springframework
spring-test
4.3.2.RELEASE
mysql
mysql-connector-java
8.0.16
com.alibaba
druid
1.1.9
junit
junit
4.12
2.3.2 第二步:创建User实体类
使用Mybatis-Plus可以不使用xml文件,而是基于一组