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

如何在非原生JPA查询中正确使用array_overlaps函数解决参数类型不匹配问题

如何在非原生JPA查询中正确使用array_overlaps函数解决参数类型不匹配问题

我想要在JPA查询中使用array_overlaps()函数,而不用显式地使用原生查询。

以下是我的@Query定义:

@Query(value = """
                SELECT view FROM FilterView view
                WHERE (:selectedIds IS NULL
                        OR array_overlaps(view.ids, (:selectedIds)) IS true)
                """)
List<FilterView> findAllByFilter(Collection<Long> selectedIds);

View Entity定义:

@Getter
@Setter
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "filter_view")
public class FilterView {

  @JdbcTypeCode(Types.ARRAY)
  @Column(name = "ids")
  private Collection<Long> ids;

  // other fields
}

View SQL文件:

DROP VIEW IF EXISTS filter_view;
CREATE VIEW filter_view AS
SELECT
    ARRAY_AGG(DISTINCT p.id) AS ids,
    -- other columns

FROM my_entity p
         LEFT JOIN ...
GROUP BY ...

在这个配置下,我遇到了以下运行时错误:

Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint[] && bytea

这个错误说明selectedIds参数被当作bytea类型处理了,尽管我的方法签名里定义的是Collection,我完全搞不懂为什么会这样。这直接导致了类型不匹配问题。

需要说明的是,这个问题不是和某类hibernate问题相关的,移除空检查(:selectedIds IS NULL OR)也解决不了问题。而且在我的测试场景中,输入值总是存在的,所以空检查的有无并不是问题的诱因。

我试过使用cast()或者treat()来转换类型,但没找到正确的用法。比如cast(:selectedIds as Collection<Long>)会直接导致编译错误。

我还试过用elements(:selectedIds)包裹参数,但同样会触发编译错误:

Caused by: org.hibernate.query.sqm.produce.function.FunctionArgumentException:
Parameter 1 of function 'array_overlaps()' requires an array type
java.util.Collection<java.lang.Long>, but argument is of type 'java.lang.Object'

请问如何正确传递Collection<Long>作为数组参数在JPA中,让array_overlaps()可以正常工作而不用原生查询?有没有一种在JPA中表示数组的替代方式,可以避免bytea转换的问题?

备注:内容来源于stack exchange,提问作者repi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:03:03