如何在Spring JPA中向jsonb_path_query传递参数
修正Spring JPA原生查询的参数传递问题
原查询存在的问题
@Query注解中的nativeQuerywu是拼写错误,正确写法为nativeQuery = true- JSONPath表达式内的参数占位符绑定方式有问题,直接在字符串中使用
?1、?2可能导致参数解析失败,同时存在潜在的SQL注入风险
修正后的查询代码
位置参数版本
@Query(value = "select jsonb_path_query(payload, '$.structures.array[*].businessRelationships.array[?1]')::text " + "from fmk_t_contract " + "where jsonb_path_exists(payload, '$.structures.array[*].businessRelationships ? (@.array[?].brlStId == ?)', jsonb_build_array(?1, ?2))", nativeQuery = true) String findByJsonValueByBrlId(int index, String brStId);
命名参数版本(可读性更强)
import org.springframework.data.repository.query.Param; // ... @Query(value = "select jsonb_path_query(payload, '$.structures.array[*].businessRelationships.array[:index]')::text " + "from fmk_t_contract " + "where jsonb_path_exists(payload, '$.structures.array[*].businessRelationships ? (@.array[:index].brlStId == :brStId)', jsonb_build_array(:index, :brStId))", nativeQuery = true) String findByJsonValueByBrlId(@Param("index") int index, @Param("brStId") String brStId);
关键修正点说明
- 修正nativeQuery配置:将错误的
nativeQuerywu改为nativeQuery = true,明确指定使用原生SQL查询 - 参数传递优化:通过
jsonb_build_array将Java方法的参数封装为JSON数组,传递给jsonb_path_exists的第三个参数,让PostgreSQL正确解析JSONPath中的占位符,避免直接在字符串中拼接参数的风险 - 命名参数优势:使用
@Param绑定参数名,让SQL中的参数与方法参数一一对应,降低因参数顺序变化导致的错误概率,提升代码可读性
内容的提问来源于stack exchange,提问作者Pankaj Mandale
相关产品推荐
相关产品推荐

