我正在使用Spring Data JPA,我的模型的属性之一是PostgreSQL中的jsonb
列。这就是它的映射方式:
@Type(type = "catalog.utils.model.JsonbType")
@Column(name = "marc", columnDefinition = "jsonb")
private Marc marc;
这个对象保存、检索和更新都很好。然后在我的存储库中,我制作了一个方法来通过某个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 +""}");
}
对我来说,在替换->其中->gt;
所以在你的情况下,它会是:
@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);