SpringBoot整合MyBatisPlus入门
- 1. MyBatisPlus概述
- 1.1 MyBatis介绍
- 1.2 MyBatisPlus特性
- 2. SpringBoot整合MyBatisPlus入门
- 2.1 创建新模块,选择Spring初始化,并配置模块相关基础信息
- 2.2 选择当前模块需要使用的依赖(JDBC即可)
- 2.3 手动添加MyBatisPlus起步依赖
- 2.4 制作用于测试的实体类与表结构
- 2.5 设置数据源参数(application.yml)
- 2.6 定义数据接口,继承BaseMapper
- 2.7 测试类中注入dao接口,测试功能
1. MyBatisPlus概述
1.1 MyBatis介绍
- MyBatisPlus(简称MP)是基于MyBatis框架基础上开发的增强型工具,旨在简化开发、提高效率
- 官网:
- https😕/mybatis.plus/
- https://mp.baomidou.com/
1.2 MyBatisPlus特性
- 无侵入:只做增强不做改变,不会对现有工程产生影响
- 强大的 CRUD 操作:内置通用 Mapper,少量配置即可实现单表CRUD操作
- 支持 Lambda:编写查询条件无需担心字段写错
- 支持主键自动生成
- 内置分页插件
- ……
2. SpringBoot整合MyBatisPlus入门
2.1 创建新模块,选择Spring初始化,并配置模块相关基础信息
2.2 选择当前模块需要使用的依赖(JDBC即可)
2.3 手动添加MyBatisPlus起步依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!-- druid 连接池 - 可选 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!-- lombok - 可选 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
</dependency>
2.4 制作用于测试的实体类与表结构
(类名与表名对应,属性名与字段名对应)
create database if not exists mybatisplus_db character set utf8;
use mybatisplus_db;
CREATE TABLE user (
id bigint(20) primary key auto_increment,
name varchar(32) not null,
password varchar(32) not null,
age int(3) not null ,
tel varchar(32) not null
);
insert into user values(null,'tom','123456',12,'12345678910');
insert into user values(null,'jack','123456',8,'12345678910');
insert into user values(null,'jerry','123456',15,'12345678910');
insert into user values(null,'tom','123456',9,'12345678910');
insert into user values(null,'make','123456',28,'12345678910');
insert into user values(null,'linda','123456',22,'12345678910');
insert into user values(null,'sida','123456',16,'12345678910');
@Data
public class User {
private Long id;
private String name;
private String password;
private Integer age;
private String tel;
}
2.5 设置数据源参数(application.yml)
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC
username: root
password: root
2.6 定义数据接口,继承BaseMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sun.domain.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserDao extends BaseMapper<User> {
}
2.7 测试类中注入dao接口,测试功能
import com.sun.dao.UserDao;
import com.sun.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class Tests {
@Autowired
private UserDao userDao;
@Test
void testGetAll() {
List<User> userList = userDao.selectList(null);
System.out.println(userList);
}
}