【问题标题】:Spring-Data-JPA native query on jsonb fieldjsonb字段上的Spring-Data-JPA本机查询
【发布时间】: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 字段一起正常工作。有没有办法让这个工作?

【问题讨论】:

标签: postgresql spring-data-jpa jsonb


【解决方案1】:

您必须在本机查询中转换值。

cast(:uuid as UUID)

所以你的查询变成了。

@Query(value = "Select * From my_table"
 + "and my_json@>'{\"object\"\\: {\"array\" \\: [{\"uuid\"\\: cast(:uuid as UUID)}]}}'",
nativeQuery = true)

【讨论】:

  • 我会试试这个,但如果是这种情况,为什么它不能作为字符串工作?
猜你喜欢
  • 1970-01-01
  • 2019-04-15
  • 2017-10-09
  • 2015-01-30
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多