Spring Boot JPA:如何查询表中的 JSON 列

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

我有一个表

casemessage
并且有以下列。我正在尝试使用
JSON
..
 搜索/查询 
Spring Framework JPA

  1. id
  2. 创建者
  3. 创建_UTC
  4. 来自_id
  5. 留言
  6. 状态
  7. 案例_id

此处

status
列存储
JSON
字符串列表。例如:

 1. [{"user_id": 1, "status": "sent"}, {"user_id": 2, "status": "delete"}]
 2. [{"user_id": 3, "status": "delete"}, {"user_id": 2, "status": "sent"},{"user_id": 1, "status": "received"}]
 3. [{"user_id": 1, "status": "received"}, {"user_id": 2, "status": "sent"}]
 4. [{"user_id": 1, "status": "delete"}, {"user_id": 3, "status": "sent"}]

我正在尝试查询

casemessage
表以获取
user_id
1
status
不是
delete

的所有行

使用

MySQL
查询,我可以查询表并获取预期结果。

这是我尝试过的查询:

 select * from casemessage  where case_Id=1 and id not in(select id from cwot.casemessage where json_contains(status, '{"status" :"delete"}') and json_contains(status, '{"user_id" : 1}'));

当我使用

Spring Framework JPA
(
Spring Boot
) 尝试此操作时,我在运行应用程序时遇到异常。这是我绑定的声明:

    @Query("select c from CaseMessage c  where c.caseId=?1 and c.id not in(select cm.id from CaseMessage cm where json_contains(status, '{\"status\": \"delete\"}') and json_contains(status, '{\"user_id\": ?2}'))")
    List<CaseMessageResponse> getAllCaseMessages(long caseId, long userId);

我返回的错误是:

 Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: ( near line 1, column 172 [select c from com.cwot.domain.CaseMessage c  where c.caseId=?1 and c.id not in(select cm.id from com.cwot.domain.CaseMessage cm where json_contains(status, '{"status": "delete"}') and json_contains(status, '{"user_id": ?1}'))]

有人可以帮我解决这个问题吗?

非常感谢任何帮助。

mysql json spring-boot spring-data-jpa
2个回答
10
投票

您必须使用本机查询才能使用 json_contains 等数据库函数:

@Query("select c from CaseMessage c  where c.caseId=?1 and c.id not in(select cm.id from CaseMessage cm where json_contains(status, '{\"status\": \"delete\"}') and json_contains(status, '{\"user_id\": ?2}'))", nativeQuery = true)
    List<CaseMessageResponse> getAllCaseMessages(long caseId, long userId);

或使用@NativeQuery注释

了解更多信息:

查询、本机查询、命名查询和类型化查询之间的区别


0
投票

我能够解决这个问题的一种方法是使用

JSON_CONTAINS(json, JSON_QUOTE(?1))
nativeQuery=true

这样,我就可以添加查询所需的额外双引号

© www.soinside.com 2019 - 2024. All rights reserved.