前言
Spring Boot 使我们能够快速、简单地创建可立即运行的独立应用。而 Mybatis Plus 3 是 Mybatis 的增强工具,提供了很多便利的功能,比如通用 CRUD 操作、分页功能等。这篇教程将带你了解如何在 Spring Boot 项目中整合 Mybatis Plus 3。
1. 创建 Spring Boot 项目
首先,我们需要创建一个 Spring Boot 项目。你可以通过许多方式来创建,比如使用 Spring Initializr、IDEA 的 Spring Initializr 插件等。创建时,记得添加 Spring Web 和 MySQL Driver 这两个依赖。
2. 添加 Mybatis Plus 依赖
在项目的 pom.xml
文件中,添加 Mybatis Plus 的依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.3.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
3. 配置数据库连接和 Mybatis Plus
在 application.yml
文件中,配置你的数据库连接信息和 Mybatis Plus 的 mapper-locations:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath:/mappers/*.xml
4. 创建实体类
在你的项目中创建一个实体类,例如 User
:
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// 省略 getter 和 setter
}
5. 创建 Mapper 接口
创建一个 UserMapper
接口,并继承 BaseMapper<User>
:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper<User> {
}
6. 创建服务类
创建一个 UserService
类,并在其中注入 UserMapper
:
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserService {
@Resource
private UserMapper userMapper;
public List<User> listAll() {
return userMapper.selectList(null);
}
}
7. 创建 Controller 类
最后,创建一个 UserController
类,并在其中注入 UserService
:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("/users")
public
List<User> listAll() {
return userService.listAll();
}
}
现在,你的 Spring Boot 项目已经成功地整合了 Mybatis Plus 3!你可以启动你的项目,然后访问 http://localhost:8080/users
来看到所有的用户信息。
注意:本教程仅用于演示如何整合 Mybatis Plus 3,实际开发中,你需要按照你自己的需求来创建数据库、实体类、Mapper 接口、服务类和 Controller 类。