✅ 一、核心概念
概念 |
说明 |
BaseMapper |
提供通用的 CRUD 方法,如 selectById , deleteById 等 |
Wrapper |
条件构造器,如 QueryWrapper , LambdaQueryWrapper |
逻辑删除 |
不物理删除数据,而是将字段 deleted 更新为 1,查询自动过滤已删除数据 |
自动填充 |
插入/更新时自动填充字段,如 create_time , update_time |
✅ 二、操作步骤(非常详细)
🔍 查询操作
1. 基础查询(按主键)
User user = userMapper.selectById(1L);
2. 条件查询(QueryWrapper)
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "张三").gt("age", 18);
List<User> users = userMapper.selectList(wrapper);
3. Lambda 条件构造器(推荐)
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
lqw.eq(User::getName, "张三").between(User::getAge, 18, 30);
List<User> users = userMapper.selectList(lqw);
4. 分页查询(需配置分页插件)
Page<User> page = new Page<>(1, 10); // 第1页,每页10条
Page<User> result = userMapper.selectPage(page, lqw);
System.out.println("总记录数:" + result.getTotal());
🗑️ 删除操作
1. 按主键删除(物理删除)
int rows = userMapper.deleteById(1L);
2. 批量删除(物理删除)
List<Long> ids = Arrays.asList(2L, 3L, 4L);
int rows = userMapper.deleteBatchIds(ids);
3. 条件删除(物理删除)
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("age", 20);
int rows = userMapper.delete(wrapper);
4. 逻辑删除(推荐)
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
@TableLogic
private Integer deleted;
userMapper.deleteById(1L); // 实际执行 UPDATE user SET deleted=1 WHERE id=1 AND deleted=0
List<User> users = userMapper.selectList(null); // 只查 deleted=0 的数据
❗ 三、常见错误与排查
错误现象 |
原因与解决方法 |
逻辑删除无效 |
实体类未加 @TableLogic ,或数据库无 deleted 字段 |
查询仍包含已删除数据 |
Mapper 未继承 BaseMapper ,或配置文件中未启用逻辑删除 |
分页查询返回全部数据 |
未配置分页插件,或配置错误(需添加 MybatisPlusInterceptor ) |
Lambda 条件字段拼写错误 |
使用 LambdaWrapper 可避免拼写错误,如 User::getName |
插入后 ID 未回填 |
实体类主键未加 @TableId(type = IdType.AUTO) 或数据库未设置自增主键 |
✅ 四、注意事项
- 逻辑删除字段建议使用
Integer
或 Boolean
类型,避免使用字符串。
- 分页插件必须手动配置,否则分页无效。
- 删除操作默认不触发自动填充,如需填充,请使用
updateById
手动设置。
- 避免使用
selectList(null)
,会触发全表扫描,建议始终带条件查询。
🚀 五、使用技巧与最佳实践
场景 |
技巧 |
条件拼接复杂 |
使用 LambdaQueryWrapper ,避免字段名拼写错误 |
多表查询 |
使用 XML 自定义 SQL 或 MyBatis-Plus 提供的 @Select 注解 |
批量操作 |
使用 saveBatch , removeBatchByIds , updateBatchById 提高效率 |
性能优化 |
使用 @TableField(select = false) 避免查询大字段 |
查询字段控制 |
使用 wrapper.select("id", "name") 只查所需字段,减少 IO |
⚙️ 六、性能优化建议
- 为查询字段加索引,避免全表扫描。
- 使用分页查询+索引字段排序,提升大数据量响应速度。
- 避免 N+1 查询:使用
select * from user where id in (...)
替代循环查询。
- 开启 SQL 性能分析插件,打印慢 SQL,便于调优。
✅ 七、完整配置示例(Spring Boot)
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
id-type: auto
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor interceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}