使用 Postgresql 的 Spring JPA 本机查询中的值进行更新

问题描述 投票:0回答:1

我正在尝试使用 Spring JPA 实现以下目标。

update test as t set
    column_a = c.column_a
from (values
    ('123', 1),
    ('345', 2) // this will be dynamic
) as c(column_b, column_a) 
where c.column_b = t.column_b;

有没有办法使用本机查询从 spring jpa 传递值?

postgresql spring-data-jpa spring-data-rest
1个回答
0
投票

我建议您首先将动态数据序列化为任意长度的 JSON 数组 - 甚至是空数组 - 像这样

[
 [1, "234"],
 [2, "345"]
]

并使用这个本机查询:

@Query(
value = "update test as t set column_a = c.column_a
         from (
          select j[0]\\:\\:integer column_a, j[1]\\:\\:text column_b
          from jsonb_array_elements (?1\\:\\:jsonb) j
         ) c
         where c.column_b = t.column_b",
nativeQuery = true
)

备注:

  • 在 JPA 中,后缀强制转换运算符
    ::
    被转义为
    \\:\\:
  • 在 PG14 之前的 PostgreSQL 下,使用箭头语法
    (j->>0)\\:\\:integer
    j->>1
    ;
© www.soinside.com 2019 - 2024. All rights reserved.