使用 JOOQ 构建复杂查询并返回 MyBatis 的 `ResultHandler`。
解读
国内互联网/金融/政企项目里,MyBatis 仍是主流 ORM,但面对多表关联、窗口函数、CTE、动态字段等复杂场景时,手写 XML 既繁琐又容易出错。
JOOQ 以类型安全的方式拼 SQL,可以把“拼 SQL”与“结果处理”解耦:
- 用 JOOQ 生成带占位符的 SQL 字符串与有序参数列表;
- 把这两份数据交给 MyBatis,复用其一级缓存、二级缓存、插件链、事务、连接池;
- 最终由 MyBatis 的
ResultHandler<T>做流式消费,避免一次性把大结果集加载到内存。
面试官真正想看的是:
- 你是否理解 JOOQ 与 MyBatis 的边界(谁拼 SQL、谁管理连接、谁映射结果);
- 能否把 JOOQ 的
Query无损转成 MyBatis 能执行的MappedStatement; - 是否熟悉
ResultHandler的游标/流式接口,以及事务边界、分页、内存控制。
知识点
-
JOOQ 的 SQL 渲染与参数绑定
DSLContext.renderNamedParams(query)只能拿到带:name的字符串,MyBatis 要求#{}占位符且顺序与List<Object>一一对应;因此必须用render()+getParams()拿到 ? 占位 SQL 与 有序 paramList。 -
MyBatis 的
SqlSession.select(String statement, Object parameter, ResultHandler<T>)
该重载方法不返回List,而是把每一条记录实时推入ResultHandler.handleResult(ResultContext<? extends T>),天然适合海量数据导出、异步消费、背压控制。 -
MappedStatement 的动态注册
复杂查询往往不在 XML 里写死,需要借助 MapperAnnotationBuilder 或 MyBatis 的LanguageDriver在运行期把 JOOQ 生成的 SQL 封装成MappedStatement,并标记statementType=STATEMENT防止 MyBatis 二次解析。 -
事务与连接复用
JOOQ 拼 SQL 时并不需要拿连接,真正执行者是 MyBatis;因此必须保证整个方法处在 Spring 的@Transactional下,连接由DataSourceUtils统一托管,避免 JOOQ 与 MyBatis 各拿各的连接导致事务失效。 -
类型安全映射
如果 JOOQ 的RecordN与 MyBatis 的ResultHandler之间不做任何转换,会得到Map<String,Object>;
想保持类型安全,需要自定义RecordUnmapper<MyDto>,把Record字段按序号塞进 DTO,再交给ResultHandler。 -
内存与性能
默认ResultHandler模式下,MyBatis 使用 ResultSetType.FORWARD_ONLY + fetchSize=-1,MySQL 驱动会逐条拉数据;
若数据库是 Oracle/PostgreSQL,需要手动设置fetchSize=1000并开启游标,否则仍会全量加载。
答案
下面给出一份可直接落地的 Spring Boot + MyBatis + JOOQ 代码,演示“JOOQ 拼复杂 SQL → MyBatis 流式返回 → ResultHandler 实时写出 CSV”的全过程,兼顾事务、类型安全、内存控制。
// 1. 定义 DTO
@Data
public class ComplexRow {
private Long orderId;
private String customerName;
private BigDecimal amount;
private LocalDateTime createTime;
}
// 2. 定义 Mapper 接口(空方法即可,仅用于绑定 ResultHandler)
@Mapper
public interface JooqQueryMapper {
void executeJooqQuery(@Param("sql") String sql,
@Param("params") List<Object> params,
ResultHandler<ComplexRow> handler);
}
// 3. 在 Service 里拼 SQL 并调用
@Service
public class ComplexQueryService {
@Autowired
private DSLContext dsl; // JOOQ
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
@Transactional(readOnly = true) // 4. 只读事务,保证连接复用
public void exportLargeData(OutputStream out) {
// 5. JOOQ 构建复杂查询:CTE + 窗口函数 + 动态条件
CommonTableExpression<?> cte = DSL.name("cte")
.as(select(ORDER.ID, ORDER.AMOUNT, ORDER.CREATE_TIME,
rowNumber().over(partitionBy(ORDER.CUSTOMER_ID)
.orderBy(ORDER.CREATE_TIME.desc())).as("rn"))
.from(ORDER)
.where(ORDER.STATUS.eq("PAID"))
.and(ORDER.CREATE_TIME.ge(
DSL.timestampAdd(currentTimestamp(), -30, DatePart.DAY))));
SelectConditionStep<Record4<Long, String, BigDecimal, LocalDateTime>> query =
dsl.with(cte)
.select(cte.field(ORDER.ID), CUSTOMER.NAME,
cte.field(ORDER.AMOUNT), cte.field(ORDER.CREATE_TIME))
.from(cte.join(CUSTOMER).on(cte.field(ORDER.CUSTOMER_ID).eq(CUSTOMER.ID)))
.where(cte.field("rn", Integer.class).le(3)); // 每个客户近 30 天 Top3
// 6. 把 JOOQ 的 SQL 转成 MyBatis 能识别的 ? 占位形式
String sql = query.getSQL(ParamType.INDEXED);
List<Object> params = query.getBindValues();
// 7. 用 MyBatis 的 ResultHandler 流式写出
ResultHandler<ComplexRow> handler = new ResultHandler<ComplexRow>() {
private CsvWriter csv = new CsvWriter(new OutputStreamWriter(out), ',');
@Override
public void handleResult(ResultContext<? extends ComplexRow> ctx) {
ComplexRow row = ctx.getResultObject();
try {
csv.writeRecord(new String[]{
row.getOrderId().toString(),
row.getCustomerName(),
row.getAmount().toString(),
row.getCreateTime().toString()
});
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
};
// 8. 手动注册 MappedStatement,避免写 XML
String msId = "jooqDynamicStatement";
if (!sqlSessionTemplate.getConfiguration().hasStatement(msId, false)) {
MappedStatement ms = new MappedStatement.Builder(
sqlSessionTemplate.getConfiguration(),
msId,
new StaticSqlSource(sqlSessionTemplate.getConfiguration(), sql),
SqlCommandType.SELECT)
.resultMaps(Collections.singletonList(
new ResultMap.Builder(
sqlSessionTemplate.getConfiguration(),
"jooqResultMap",
ComplexRow.class,
Arrays.asList(
new ResultMapping.Builder(
sqlSessionTemplate.getConfiguration(), "orderId")
.column("ID").build(),
new ResultMapping.Builder(
sqlSessionTemplate.getConfiguration(), "customerName")
.column("NAME").build(),
new ResultMapping.Builder(
sqlSessionTemplate.getConfiguration(), "amount")
.column("AMOUNT").build(),
new ResultMapping.Builder(
sqlSessionTemplate.getConfiguration(), "createTime")
.column("CREATE_TIME").build()
)).build()))
.statementType(StatementType.STATEMENT) // 9. 禁止 MyBatis 二次解析
.fetchSize(1000) // 10. 控制每次拉取条数
.build();
sqlSessionTemplate.getConfiguration().addMappedStatement(ms);
}
// 11. 执行
sqlSessionTemplate.select(msId, params, handler);
}
}
关键步骤回顾:
- JOOQ 只负责拼 SQL,不拿连接;
- MyBatis 负责执行、缓存、事务、流式读取;
- ResultHandler 实时消费,内存占用 O(1);
- fetchSize/StatementType/只读事务 三管齐下,保证性能与一致性。
拓展思考
-
分页场景
如果前端需要分页,不要把ResultHandler用于普通分页,而是让 JOOQ 拼完 SQL 后,再用 MyBatis 的RowBounds或 PageHelper 插件做内存分页;
只有导出/ETL/大数据量聚合才用ResultHandler。 -
多数据源
当项目里同时存在 MySQL、Oracle、SQL Server 时,JOOQ 的 SQL 方言要与目标数据源一致,否则生成的函数(如date_add)在 Oracle 会报错;
可以通过DSLContext的Settings.withRenderFormatted(true).withRenderNameStyle(RenderNameStyle.LOWER)统一风格,再让 MyBatis 执行。 -
插件扩展
MyBatis 的ResultHandler执行链路上可以植入自定义插件,例如:- 对每条记录做 脱敏/加密;
- 实时写入 Kafka/RocketMQ;
- 统计 QPS/RT 指标并上报 Prometheus。
-
与 Spring Batch 整合
把ResultHandler封装成ItemReader<ComplexRow>,结合 Spring Batch 的 chunk 机制,可实现分布式、断点续传、失败重试的亿级数据同步任务。 -
未来趋势
国内云原生项目开始尝试 MyBatis-Flex、MyBatis-Plus-JOIN 等“无 XML”方案,但 JOOQ 的类型安全+窗口函数+CTE 能力仍不可替代;
掌握“JOOQ 拼 SQL + MyBatis 执行 + ResultHandler 流式”的混合模式,能在面试中体现深度与广度,成为架构组眼中的“SQL 终结者”。