Mybatis Plus 怎么写自定义 SQL?你掌握关键点了吗?
- 工作日记
- 30天前
- 53热度
- 0评论
虽然MyBatis Plus提供了强大的条件构造器Wrapper和通用Mapper,但在实际开发中,我们总会遇到复杂业务场景:多表关联查询、批量特殊字段处理、自定义存储过程调用等。这时掌握自定义SQL的正确使用姿势,就成为区分普通开发者和高级工程师的重要分水岭。
一、两种核心实现方式对比
1.1 XML映射文件方式(推荐)
步骤说明:
- 在resources/mapper目录创建对应XML文件
- 定义SQL语句时使用
${ew.customSqlSegment}
获取Wrapper条件 - Mapper接口使用
@Select
注解或直接定义方法
<select id="selectCustomList" resultType="YourEntity">
SELECT FROM user ${ew.customSqlSegment}
</select>
1.2 注解方式实现
@Select("SELECT FROM user ${ew.customSqlSegment}")
List<User> selectByCustomWrapper(@Param(Constants.WRAPPER) Wrapper<User> wrapper);
二、高级技巧:突破MyBatis Plus的限制
2.1 自定义SQL注入器
实现流程:
- 继承DefaultSqlInjector
- 重写getMethodList方法
- 注册自定义方法
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertBatchSomeColumn());
return methodList;
}
}
2.2 类型处理器实战
处理JSON字段等特殊类型时,需自定义TypeHandler:
@MappedTypes(JSONObject.class)
public class JsonTypeHandler extends BaseTypeHandler<JSONObject> {
// 实现类型转换逻辑
}
三、性能优化关键点
3.1 批处理优化方案
- 使用sqlSessionFactory批量模式
- 合理设置batchSize(建议500到1000)
- 事务边界控制
3.2 分页插件深度配置
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
四、调试排错技巧
4.1 日志配置方案
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>
4.2 SQL执行分析
使用p6spy组件捕获完整SQL:
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:mysql://localhost:3306/db
五、最佳实践推荐
- 推荐使用Ruoyi-Vue-Pro开源项目实践(项目地址:https://github.com/YunaiV/ruoyi-vue-pro)
- 复杂查询优先选择XML方式
- 批量操作务必配置事务
- 多使用ResultMap处理复杂结果集
掌握这些核心要点后,你将能游刃有余地应对各种复杂SQL场景。建议结合官方文档和开源项目实践,在真实业务场景中不断打磨SQL编写能力。正如开源社区倡导的「参与即成长」理念,欢迎开发者们共同完善MyBatis Plus生态,让ORM框架更加强大易用。