SpringBoot 整合 MybatisPlus 具体实现步骤为 :
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(1,'Tom','tom',3,'18866668888');
insert into user values(2,'Jerry','jerry',4,'16688886666');
insert into user values(3,'Jock','123456',41,'18812345678');
insert into user values(4,'传智播客','itcast',15,'4006184000');
pom.xml
补全依赖 <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
说明 :
5. 添加 MP 的相关配置信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
public class User {
private Long id;
private String name;
private String password;
private Integer age;
private String tel;
//setter...getter...toString方法略
}
@Mapper
public interface UserDao extends BaseMapper<User>{
}
@SpringBootApplication
public class MybatisPlus01QuickstartApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlus01QuickstartApplication.class, args);
}
}
说明 :Dao 接口要想被容器扫描到,有两种解决方案:
@Mapper
注解,并且确保 Dao 处在引导类所在包或其子包中 @MapperScan
注解,其属性为所要扫描的 Dao 所在包 @Mapper
就可以不写。@SpringBootTest
class MybatisPlus01QuickstartApplicationTests {
@Autowired
private UserDao userDao;
@Test
void testGetAll() {
List<User> userList = userDao.selectList(null);
System.out.println(userList);
}
}
说明:
userDao 注入的时候下面有红线提示的原因是什么?
跟之前整合 MyBatis 相比,你会发现我们不需要在 DAO 接口中编写方法和 SQL 语句了,只需要继承
BaseMapper
接口即可。整体来说简化很多。
MyBatisPlus(简称 MP)是基于 MyBatis 框架基础上开发的增强型工具,旨在简化开发、提高效率
MyBatisPlus 的官网为:https://mp.baomidou.com/
MyBatisPlus 是 Mybatis 最好的搭档
MyBatisPlus 的特性 :