Mybatis-Plus:持久层数据的高效处理(一)快速入门
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window) 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
快速入门
1. 准备数据模型
CREATE DATABASE `test`;
USE `test`;
DROP TABLE IF EXISTS `test1`;
CREATE TABLE `test1`(
`id` INT AUTO_INCREMENT NOT NULL COMMENT '唯一id',
`username` VARCHAR(20) DEFAULT '' COMMENT '用户名',
`password` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '密码',
`name` VARCHAR(20) DEFAULT '' COMMENT '姓名',
`age` INT,
`gender` TINYINT(1) DEFAULT 2 COMMENT '1为男,0为女 2保密',
`phone` VARCHAR(11) DEFAULT '' COMMENT '电话',
`email` VARCHAR(50) DEFAULT '' COMMENT '邮箱',
`avatar` VARCHAR(100) DEFAULT NULL COMMENT '头像地址',
`department` VARCHAR(20),
`salary` DOUBLE(10,5),
`address` VARCHAR(50),
`status` TINYINT(1) DEFAULT 1 COMMENT '1为正常 0为停用',
PRIMARY KEY(`id`),
UNIQUE KEY`idx_username`(`username`)
);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('zhangsan111','zhangsan111','张三',35,1,'13512345678','13512345678@qq.com','','销售部',15000,'北京市海淀区中关村',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('lisi111','lisi111','李四',28,1,'15698765432','15698765432@qq.com','','市场营销部',12000,'上海市浦东新区张江',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('wangwu111','wangwu111','王五',42,1,'13811112222','13811112222@qq.com','','研发部',20000,'广东省深圳市南山区科技园',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('zhaoliu111','zhaoliu111','赵六',25,0,'13933334444','13933334444@qq.com','','人力资源部',10000,'江苏省南京市玄武区',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('liuqi111','liuqi111','刘七',22,0,'13655556666','13655556666@qq.com','','财务部',18000,'四川省成都市高新区',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('zhouba111','zhouba111','周八',33,1,'15077778888','15077778888@qq.com','','操作部',13500,'天津市滨海新区',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('wujiu111','wujiu111','吴九',27,0,'15899990000','15899990000@qq.com','','销售部',14000,'销售部','湖北省武汉市洪山区',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('zhengshi111','zhengshi111','郑十',29,1,'15698765432','15698765432@qq.com','','市场营销部',12500,'浙江省杭州市滨江区',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('sunshiyi111','sunshiyi111','孙十一',31,1,'18722223333','18722223333@qq.com','','研发部',19000,'河北省石家庄市裕华区',1);
INSERT INTO `test1`(username,password,name,age,gender,phone,email,avatar,department,salary,address,status) VALUES('zhushier111','zhushier111','朱十二',28,0,'13666667777','13666667777@qq.com','','人力资源部',9500,'福建省厦门市思明区',1);
2. 创建文件并导入依赖
创建spring项目后,在application的主函数入口上加入mapper扫描注解@MapperScan("com.vinta.test.mapper")
,这里替换成自己的mapper包的路径。
//依赖包导入
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.vinta.my_test.mapper")
public class MyTestApplication {
public static void main(String[] args) {
SpringApplication.run(MyTestApplication.class, args);
}
}
然后导入mybatis和jdbc驱动依赖,其他的spring依赖不多赘述。
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</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>
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- jdbc驱动-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- hikari数据库连接池-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.1.0</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
</dependencies>
3. 配置文件和启动类
server:
port: 8080 # 项目运行端口,默认 8080
spring:
datasource:
# 指定数据库驱动类
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
hikari: # 数据库连接池使用 Hikari
minimum-idle: 5 # 连接池中最小空闲连接数
maximum-pool-size: 20 # 连接池中允许的最大连接数
auto-commit: true # 是否自动提交事务
idle-timeout: 30000 # 连接在连接池中闲置的最长时间,超过这个时间会被释放。
pool-name: MP-HikariCP # 自定义连接池的名字
max-lifetime: 1800000 # 连接在连接池中的最大存活时间,超过这个时间会被强制关闭。
connection-timeout: 30000 # 连接的超时时间
connection-test-query: SELECT 1 # 用于测试连接是否可用的SQL查询
4.利用mybatisX代码生成器生成实体类
选中数据库中的表,右键弹出菜单,选择MybatisX-Generator如果没有插件的小伙伴可以直接在setting中的plugins下载即可。
这里选择MP3注解和lombok注解
5.单元测试MP生成的mapper实现的CRUD接口
在springboot测试类中注入组件
import com.vinta.my_test.entity.Test1;
import com.vinta.my_test.mapper.Test1Mapper;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MyTestApplicationTests {
@Resource
private Test1Mapper test1Mapper;
}
insert测试
@Test
void insertTest() {
Test1 test1 = new Test1();
test1.setUsername("xiaoye111");
test1.setPassword("123456");
test1.setName("xiaoye");
test1.setAge(18);
test1.setGender(1);
test1.setPhone("12345678901");
test1.setEmail("123@qq.com");
test1.setDepartment("IT");
test1.setSalary(10000.0);
test1.setStatus(1);
test1.setAvatar("123.jpg");
test1.setAddress("湖北省武汉市江夏区");
System.out.println(test1Mapper.insert(test1));
//打印 1
}
select测试
@Test
void selectTest() {
System.out.println(test1Mapper.selectById(8));
}
//Test1 [Hash = 1585078543, id=8, username=xiaoye111, password=123456, name=xiaoye, age=18, gender=1, phone=12345678901, email=123@qq.com, avatar=123.jpg, department=IT, salary=10000.0, address=湖北省武汉市江夏区, status=1, serialVersionUID=1]
不论是inset、select、update还是delete接口都是可以顾名思义的,这里就不再一一赘述。主要留到下一章讲解自定义sql语句。