1.基本简介
MyBatis-Plus 是一个基于 MyBatis 的增强工具,旨在简化开发、提高效率。它在 MyBatis 的基础上进行扩展,只做增强不做改变,不会对现有的 MyBatis 架构产生任何影响。
主要特性
-
无侵入:MyBatis-Plus 在 MyBatis 的基础上进行扩展,只做增强不做改变,引入 MyBatis-Plus 不会对现有的 MyBatis 架构产生任何影响。
-
依赖少:仅仅依赖 MyBatis 以及 MyBatis-Spring。
-
损耗小:启动即会自动注入基本 CRUD,性能基本无损耗,直接面向对象操作。
-
通用 CRUD 操作:内置通用 Mapper、通用 Service,仅需少量配置即可实现单表大部分 CRUD 操作。
-
多种主键策略:支持多达 4 种主键策略(内含分布式唯一 ID 生成器),可自由配置,完美解决主键问题。
-
支持 ActiveRecord:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可实现基本 CRUD 操作。
-
支持代码生成:采用代码或者 Maven 插件可快速生成 Mapper、Model、Service、Controller 层代码,支持模板引擎。
-
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于写基本 List 查询。
-
内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能有效解决慢查询。
-
内置全局拦截插件:提供全表 delete、update 操作智能分析阻断,预防误操作。
2.准备环境(依赖导入)
确保项目中引入 MyBatis-Plus 依赖(以 Maven 为例):
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version> <!-- 采用最新稳定版本 -->
<scope>provided</scope> <!-- 编译时使用,运行时无需 -->
</dependency>
3.定义实体类
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("user") // 对应数据库表名
public class User {
@TableId // 主键注解
private Long id;
private String name;
private Integer age;
private String email;
//@TableId(type = IdType.AUTO) // 主键自增
//private Long id;
//private String name;
//@TableField("user_age") // 映射非驼峰命名的字段
//private Integer age;
//private String email;
//@TableField(exist = false) // 非数据库字段
//private String extraInfo;
}
4.继承Mapper接口
继承 BaseMapper 即可获得通用 CRUD (增删改查)方法:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> {
// 无需编写方法,BaseMapper 已提供通用 CRUD
}
5.单表 CRUD 操作示例(增删改查)
以下是在 Service 层使用 MyBatis-Plus 提供的方法实现 CRUD 的示例:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
// ============== 增 ==============
public boolean saveUser(User user) {
return userMapper.insert(user) > 0;
}
// ============== 删 ==============
public boolean removeUser(Long id) {
// 按 ID 删除
return userMapper.deleteById(id) > 0;
}
public boolean removeUserByCondition(String name, Integer age) {
// 按条件删除(例如:删除 name=张三 且 age=20 的记录)
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", name).eq("age", age);
return userMapper.delete(wrapper) > 0;
}
// ============== 改 ==============
public boolean updateUser(User user) {
// 按 ID 更新(null 值字段不会更新)
return userMapper.updateById(user) > 0;
}
public boolean updateUserByCondition(User user, String oldName) {
// 按条件更新(例如:将 name=张三 的记录更新为新的 user 对象)
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.eq("name", oldName);
return userMapper.update(user, wrapper) > 0;
}
// ============== 查 ==============
public User getUserById(Long id) {
// 按 ID 查询
return userMapper.selectById(id);
}
public List<User> listUsers() {
// 查询所有记录
return userMapper.selectList(null);
}
public List<User> listUsersByCondition(String name, Integer age) {
// 按条件查询(例如:查询 name=张三 且 age>20 的记录)
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", name).gt("age", age);
return userMapper.selectList(wrapper);
}
public IPage<User> pageUsers(Integer pageNum, Integer pageSize) {
// 分页查询(第 1 页,每页 10 条)
Page<User> page = new Page<>(pageNum, pageSize);
return userMapper.selectPage(page, null);
}
public IPage<User> pageUsersByCondition(Integer pageNum, Integer pageSize, String name) {
// 带条件的分页查询
Page<User> page = new Page<>(pageNum, pageSize);
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name", name); // 模糊查询
return userMapper.selectPage(page, wrapper);
}
}
6.分页插件配置
若需使用分页功能,需配置分页拦截器:
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
7.测试示例
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public boolean save(@RequestBody User user) {
return userService.saveUser(user);
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Long id) {
return userService.removeUser(id);
}
@PutMapping
public boolean update(@RequestBody User user) {
return userService.updateUser(user);
}
@GetMapping("/{id}")
public User get(@PathVariable Long id) {
return userService.getUserById(id);
}
@GetMapping
public List<User> list() {
return userService.listUsers();
}
}