前言
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
MyBatis-Plus 可以简化我们大量工作时间,很多的CRUD代码它都可以自动化完成,类似JPA、tk-mapper。话不多说开始吧。
以下参考自官方文档,需要搭配去读:官方文档 - 快速开始
一、快速开始
注意:这里我自己使用的mysql数据库,而不是官方文档中的H2数据库。
1.数据库准备
mysql中创建数据库,执行官方文档提供的sql数据。
2.添加依赖
创建一个spring boot项目,添加依赖。核心:添加mybatis-plus的依赖。
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7</version>
</dependency>
完整依赖如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
3.配置application.yaml文件
数据库配置。
# DataSource Config
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
4.创建类和接口
按照官方文档创建 User 类和 UserMapper 接口,接口需要继承 BaseMapper
并且在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 接口。
5.测试
编写测试类运行。
这里暑促和时使用了 JDK 8 的新特性 “方法引用” 。
@Test
public void testSelect() {
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
二、总结
1.总结
MyBatis-Plus引入后,我们不用写 XML ,他就已经帮我们实现了简单的 CRUD。同时,他的功能还不仅如此,还有很多强大的功能。我们来看下面官方文档的“小节”吧。
2.小节
通过以上几个简单的步骤,我们就实现了 User 表的 CRUD 功能,甚至连 XML 文件都不用编写!
从以上步骤中,我们可以看到集成MyBatis-Plus非常的简单,只需要引入 starter 工程,并配置 mapper 扫描路径即可。
但 MyBatis-Plus 的强大远不止这些功能,想要详细了解 MyBatis-Plus 的强大功能?那就继续往下看吧!
接下来的内容可以继续查看官方文档。
三、扩展(增加配置)
增加日志输出配置。
只需要在application.yaml配置文件中,增加mybatis-plus的日志配置即可。
# DataSource Config
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
# mybatis-plus Config
mybatis-plus:
configuration:
# 日志配置(这里使用标准输出实现)
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
MyBatis 配置文件位置,如果您有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。
MyBatis Configuration 的具体内容请参考 MyBatis 官方文档