簡體   English   中英

Spring 數據 JPA:按 json 屬性查找

[英]Spring Data JPA: find by json property

我正在使用 Spring 數據 JPA 和我的 model 的屬性之一是 Z39Z6F391EE58972846F中的jsonb這是它的映射方式:

@Type(type = "catalog.utils.model.JsonbType")
@Column(name = "marc", columnDefinition = "jsonb")
private Marc marc;

這個 object 被保存、檢索和更新得很好。 然后在我的存儲庫中,我創建了一個方法來通過某個json屬性進行檢索。 此查詢在 PostgreSQL 中運行良好:

public interface AuthorityRepository  extends JpaRepository<Authority, Integer>, JpaSpecificationExecutor<Authority> {

    @Query(
            value = "SELECT * FROM my_table where marc -> 'controlNumber' = :controlNumber",
            nativeQuery = true
    )
    List<Authority> findAuthoritiesByControlNumber(@Param("controlNumber") String controlNumber);
}

當我嘗試使用我的存儲庫的這種方法時,我收到此錯誤: org.hibernate.exception.SQLGrammarException: could not extract ResultSet

在控制台中,我看到了按照我描述的方式執行的查詢和這條錯誤消息,我覺得這很令人困惑,因為在 PostgreSQL 中直接執行相同的查詢時可以正常工作。

ERROR SqlExceptionHelper ERROR: operator does not exist: jsonb = character varying
  Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

通過這些代碼是否可以識別我做錯了什么?

我找到了解決辦法。 這是我的存儲庫:

public interface AuthorityRepository  extends JpaRepository<Authority, Integer>, JpaSpecificationExecutor<Authority> {

    @Query(
            value = "SELECT * FROM my_tables where marc @> CAST(:jsonString as jsonb)",
            nativeQuery = true
    )
    List<Authority> findAuthoritiesByJsonProperty(@Param("jsonString")  String jsonString);
}

這就是我查詢它的方式:

public List<Authority> getAuthoritiesByControlNumber(String controlNumber) {
    return this.repo.findAuthoritiesByJsonProperty("{\"controlNumber\": \""+ controlNumber +"\"}");
}

對我來說,將 -> 替換為 ->> 后類似的查詢有效

因此,在您的情況下,它將是:

@Query(
        value = "SELECT * FROM my_table where marc ->> 'controlNumber' = :controlNumber",
        nativeQuery = true
)
List<Authority> findAuthoritiesByControlNumber(@Param("controlNumber") String controlNumber);
}

這是我的查詢:

@Query(nativeQuery = true, value = "SELECT * FROM myschema.mytable WHERE myjsonbcolomn ->> 'order_number' = :orderNumber")
  List<InvoiceDao> findByOrderNumber(@Param("orderNumber") String orderNumber);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM