如何修复org.postgresql.util.PSQLException:错误:op ANY/ALL(数组)需要右侧的



我有一个SQL查询

select t.id as id, t.color as color from test_data t where t.id = ANY(?1) and t.color=?2

如何将值数组传递给ANY(?1)

em.createNamedQuery("Test.getTestData", Tuple.class)
.setParameter(1, arrayOfIds<----___can_I_pass_an_array___?____)
.setParameter(2, yellow)
.unwrap(NativeQuery.class)
.addScalar("id", LongType())
.addScalar("color", new StringType())

我收到一个错误

Caused by: org.postgresql.util.PSQLException: ERROR: op ANY/ALL (array) requires array on right side
Position: 507
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553) ~[postgresql-42.2.18.jar!/:42.2.18]

我看到了两种可能的方法:

  1. 您可以将= ANY(?1)语句转换为in (?1)。正如这里所解释的,它们具有相同的含义。然后通过List<Long>而不是Long[]
List<Long> ids = new ArrayList<>();
List<Object[]> result = em.createNativeQuery(
"select id, color from test_data where id in (:ids)")
.setParameter("ids", ids)
.getResultList();
  1. 您可以添加以下依赖项:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.10.1</version>
</dependency>

如果您使用hibernate 5.4、5.3或5.2,然后以以下方式重写查询:

import com.vladmihalcea.hibernate.type.array.LongArrayType;
Long[] ids = {1L, 3L};
List<Object[]> result = em.createNativeQuery(
"select id, color from test_data where id = ANY(:ids)")
.unwrap(org.hibernate.query.NativeQuery.class)
.setParameter("ids", ids, LongArrayType.INSTANCE)
.getResultList();

您也可以编写自己的hibernate自定义基本类型,而不是添加额外的依赖项,但如果没有适当的经验,这可能会带来很大的问题。

相关内容

最新更新