如何使用Spring JPA原生查询在'where in'子句中使用元组

w46czmvw  于 7个月前  发布在  Spring
关注(0)|答案(1)|浏览(73)

我想在PostgreSQL 13.2中的where in子句中使用2列。我通过执行以下查询来测试它

select * from collision_danger_pair_contexts 
where 
(first_target_id, second_target_id) 
in
( ('63efc3d9-8fc7-4b39-a9ce-b926dae4e104', '63efc3d9-8fc7-4b39-a9ce-b926dae4e105') );

成功了
现在的问题是如何使用Spring Data JPA实现相同的功能。我尝试了以下查询

@Query(
    nativeQuery = true,
    value = """
            SELECT * FROM collision_danger_pair_contexts ctx
            WHERE (ctx.first_target_id, ctx.second_target_id) IN (:targetIds)
            """
)
List<CollisionDangerPairContext> findByTarget1IdAndTarget2Id(@Param("targetIds") List<UUID[]> targetIds);

其中targetIds包含UUID数组的列表。每个数组的长度为2。
但我有一个错误:

Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: record = bytea
      Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

在我运行查询之前,我的直觉告诉我,我太乐观了,希望它能起作用,但我不明白我应该如何以及在哪里进行“选角”。
我还尝试将参数更改为

List<List<UUID>> targetIds

但也没成功什么是正确的语法/转换?
对我来说最好的办法就是

List<org.apache.commons.lang3.tuple.ImmutablePair<UUID, UUID>> targetIds
t30tvxxf

t30tvxxf1#

我会将UUID数组列表序列化为2-dim JSON数组,即

[
  ["63efc3d9-8fc7-4b39-a9ce-b926dae4e104", "63efc3d9-8fc7-4b39-a9ce-b926dae4e105"],
  ["63efc3d9-8fc7-4b39-a9ce-b926dae4e106", "63efc3d9-8fc7-4b39-a9ce-b926dae4e107"],
  ["63efc3d9-8fc7-4b39-a9ce-b926dae4e108", "63efc3d9-8fc7-4b39-a9ce-b926dae4e109"]
]

并将其作为参数传递给本机查询:

select * from collision_danger_pair_contexts cdpc
where exists
(
 select from json_array_elements((:targetIds)::json) j
 where j ->> 0 = cdpc.first_target_id::text
   and j ->> 1 = cdpc.second_target_id::text
);

相关问题