You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jooq中实现带参数绑定的JSONB数组查询?

使用Jooq安全调用jsonb_exists_all实现JSONB数组条件查询

你完全可以通过Jooq的原生API实现安全的参数绑定,彻底避免字符串拼接带来的SQL注入风险,具体有两种实现方式:

方式一:通用函数调用(适配所有Jooq版本)

直接用DSL.function构造jsonb_exists_all函数调用,配合DSL.array安全传递参数数组:

import static org.jooq.impl.DSL.*;

// 定义需要匹配的角色集合
List<String> requiredRoles = List.of("ONE", "TWO");

Flux.from(dsl.selectFrom(MyTable.MYTABLE)
        .where(function("jsonb_exists_all", Boolean.class,
            // 等价于原生SQL中的 data -> 'roles'
            MyTable.MYTABLE.DATA.get("roles"),
            // 安全构造PostgreSQL数组参数,自动绑定
            array(requiredRoles.toArray(new String[0]))
        ))
        .map(record -> record.into(MyTableDto.class))
        .collectList();

方式二:Jooq 3.17+ 封装方法(更简洁类型安全)

Jooq 3.17及以上版本已经为JSONB数组封装了existsAll方法,直接调用即可:

// 定义需要匹配的角色集合
List<String> requiredRoles = List.of("ONE", "TWO");

Flux.from(dsl.selectFrom(MyTable.MYTABLE)
        .where(MyTable.MYTABLE.DATA.get("roles").existsAll(requiredRoles))
        .map(record -> record.into(MyTableDto.class))
        .collectList();

为什么这样安全?

两种方式都是通过Jooq的参数绑定机制传递参数,最终会生成带占位符的PreparedStatement,参数值不会直接拼接到SQL字符串中,从根源上避免了SQL注入风险,和手写原生PreparedStatement的安全性一致。

内容的提问来源于stack exchange,提问作者Dmtry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 16:25:16