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

如何在JPQL原生查询中传递字符串参数至PostgreSQL数组字段

问题解决:JPA原生查询中PostgreSQL数组类型的参数传递

错误原因

你的原查询手动拼接了数组的字符串格式'{:productCode}',这会导致参数被当作普通字符串处理,而非PostgreSQL的数组类型,因此无法正确匹配数组字段product_code的@>包含判断逻辑。

正确解决方案

方案1:单产品编码查询(参数为String)

修改@Query语句,使用PostgreSQL的数组构造函数array[:productCode]生成单元素数组,让JPA自动完成参数绑定:

@Query(value = "select * from default_price_view where product_code @> array[:productCode]", nativeQuery = true)
Page<DefaultPriceView> findDefaultPricesByProductCode(Pageable pageable,
    @Param("productCode") String productCode);

方案2:多产品编码查询(参数为List)

如果需要支持同时传入多个产品编码,可将参数类型改为List<String>,同样用数组构造函数处理:

@Query(value = "select * from default_price_view where product_code @> array[:productCodes]", nativeQuery = true)
Page<DefaultPriceView> findDefaultPricesByProductCode(Pageable pageable,
    @Param("productCodes") List<String> productCodes);

补充说明

  • PostgreSQL的@>运算符用于判断左侧数组是否包含右侧数组的所有元素,上述方案中通过array[:param]将字符串/字符串列表转为PostgreSQL数组类型,确保类型匹配。
  • 避免手动拼接数组的字符串格式(如'{xxx}'),这种写法会引发类型不匹配或SQL注入风险,始终依赖JPA的参数绑定机制处理类型转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:05:19