【发布时间】:2018-12-14 04:08:04
【问题描述】:
鉴于以下 JSON 以 jsonb 形式存储在 postgres 表中:
{
"object" : {
"array" [
{
"uuid" : "34ad3558-a3e7-43d0-826f-afddce255b20"
}
]
}
}
我有一个有效的查询来搜索 JSON 文档中是否存在 field 值:
select * from my_table
where my_json@>'{"object": {"array" : [{"field": "34ad3558-a3e7-43d0-
826f-afddce255b20"}]}}';
但是,当我尝试使用 JPARepository 上的本机查询在 Spring-Data-JPA 中复制此查询时,我不断收到以下异常:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter with that position [1] did not exist
我最初尝试过:
@Query(value = "Select * From my_table"
+ "and my_json@>'{\"object\": {\"array\" : [{\"uuid\": \"?1\"}]}}'",
nativeQuery = true)
Set<MyEntity> myQuery(UUID uuid);
在此之后,我尝试将参数与@Param 绑定:
@Query(value = "Select * From my_table"
+ "and my_json@>'{\"object\"\\: {\"array\" \\: [{\"uuid\"\\: \":uuid\"}]}}'",
nativeQuery = true)
Set<MyEntity> myQuery(@Param("uuid") UUID uuid);
之后我尝试将 UUID 转换为字符串:
@Query(value = "Select * From my_table"
+ "and my_json@>'{\"object\"\\: {\"array\" \\: [{\"uuid\"\\: \":uuid\"}]}}'",
nativeQuery = true)
Set<MyEntity> myQuery(@Param("uuid") String uuid);
仍然没有任何效果。 JPA 实体如下所示:
@Entity
public class MyEntity {
@Id
private long id;
@Column("my_json")
private MyJson myJson
}
其他涉及实体的查询可以与绑定到 MyJson 实体的 jsonb 字段一起正常工作。有没有办法让这个工作?
【问题讨论】:
-
我在这个答案stackoverflow.com/a/47898476/9080066 中找到了解决方案。不过,我仍然对其他解决方案持开放态度。
标签: postgresql spring-data-jpa jsonb