MyBatis-Plus 使用技巧
MyBatis-Plus(简称 MP)是一个基于 MyBatis 的增强工具,它在 MyBatis 的基础上提供了更多的便捷功能,比如内置的 CRUD 操作、条件构造器、分页查询等。本文将分享一些 MyBatis-Plus 的实用技巧,帮助你更高效地使用这个框架。
1. 快速入门配置
在项目中引入 MyBatis-Plus 非常简单,只需在 pom.xml
中添加依赖:
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3</version>
</dependency>
然后在 Spring Boot 的配置文件中启用 MyBatis-Plus:
mybatis-plus:mapper-locations: classpath*:/mapper/**/*.xmltype-aliases-package: com.example.entityconfiguration:map-underscore-to-camel-case: true
完成这些基础配置后,你就可以开始使用 MP 的强大功能了。
2. 基础 CRUD 操作
MyBatis-Plus 提供了 BaseMapper
接口,内置了常用的 CRUD 方法。假设有一个实体类 User
:
@TableName("t_user")
public class User {@TableId(type = IdType.AUTO)private Long id;private String name;private Integer age;// getters and setters
}
定义对应的 Mapper 接口:
public interface UserMapper extends BaseMapper<User> {
}
常用方法示例
- 插入数据:
User user = new User();
user.setName("张三");
user.setAge(25);
userMapper.insert(user);
- 根据 ID 查询:
User user = userMapper.selectById(1L);
- 更新数据:
User user = new User();
user.setId(1L);
user.setAge(26);
userMapper.updateById(user);
- 删除数据:
userMapper.deleteById(1L);
这些方法简单易用,极大减少了手写 SQL 的工作量。
3. 条件构造器(Wrapper)的妙用
MP 的条件构造器 QueryWrapper
和 UpdateWrapper
是非常强大的工具,可以动态构建 SQL 条件。
示例:动态查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "张三") // 等于.ge("age", 20) // 大于等于.orderByDesc("id"); // 按 ID 降序
List<User> users = userMapper.selectList(wrapper);
技巧:避免空值干扰
在实际开发中,参数可能是动态传入的,可能为空。可以用 isNotEmpty
或 isNotNull
判断:
QueryWrapper<User> wrapper = new QueryWrapper<>();
String name = null; // 假设从前端传入
if (StringUtils.isNotEmpty(name)) {wrapper.eq("name", name);
}
wrapper.ge("age", 18);
List<User> users = userMapper.selectList(wrapper);
4. 分页查询
MyBatis-Plus 内置了分页插件,使用起来非常方便。首先在配置类中启用分页插件:
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;
}
然后在代码中使用:
Page<User> page = new Page<>(1, 10); // 当前页为 1,每页 10 条
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("age", 25);
Page<User> result = userMapper.selectPage(page, wrapper);
System.out.println("总记录数: " + result.getTotal());
System.out.println("结果: " + result.getRecords());
5. 逻辑删除
MyBatis-Plus 支持逻辑删除功能,只需在实体类字段上添加注解,并配置全局逻辑删除规则。
配置逻辑删除
在实体类中:
@TableName("t_user")
public class User {@TableId(type = IdType.AUTO)private Long id;private String name;private Integer age;@TableLogicprivate Integer deleted; // 0 未删除,1 已删除
}
在 application.yml
中配置:
mybatis-plus:global-config:db-config:logic-delete-field: deletedlogic-delete-value: 1logic-not-delete-value: 0
使用逻辑删除
调用 deleteById
方法时,数据不会被物理删除,而是将 deleted
字段置为 1:
userMapper.deleteById(1L); // 逻辑删除
查询时,MP 会自动过滤掉 deleted = 1
的记录。
6. 自定义 SQL
虽然 MP 提供了很多内置方法,但有时仍需手写 SQL。这时可以通过 @Select
或 XML 文件实现。
示例:自定义查询
在 Mapper 接口中:
public interface UserMapper extends BaseMapper<User> {@Select("SELECT * FROM t_user WHERE age > #{age}")List<User> selectByAge(@Param("age") Integer age);
}
调用:
List<User> users = userMapper.selectByAge(20);
7. 性能优化建议
- 避免滥用 Wrapper:条件构造器虽然强大,但复杂的条件拼接可能导致性能下降,建议在复杂场景下手写 SQL。
- 开启 SQL 日志:在开发阶段,启用 MP 的 SQL 日志,检查生成的 SQL 是否符合预期:
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- 合理使用索引:MP 的自动化操作不会自动优化数据库查询,记得为常用字段建立索引。
8. 常见问题与解决
Q:字段未映射到数据库?
A:检查实体类是否正确使用 @TableName
、@TableId
和 @TableField
注解。
Q:分页查询总记录数为 0?
A:确认分页插件是否正确配置,且数据库方言(DbType
)是否匹配。
总结
MyBatis-Plus 是一个功能强大且易用的 ORM 框架,通过内置的 CRUD、条件构造器和分页插件,可以大幅提升开发效率。掌握以上技巧后,你可以更灵活地应对各种开发场景。希望这篇博文对你有所帮助!
如果有其他问题,欢迎留言交流!