java—检索couchbase文档| spring中存储的json对象数组

jecbmhm3  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(327)

如何检索存储在couchbase文档中的json对象数组并将其存储在相应的列表中,例如 List<ProjectSummary> 使用 spring-data ?
以下是couchbase上名为“项目摘要”的文档内容-

  1. [
  2. {
  3. "id": "1",
  4. "title": "New API",
  5. "owner_id": "dsdssdsd445d",
  6. "description": "Yh A Testin API",
  7. "status": "unactiveAPI"
  8. },
  9. {
  10. "id": "2",
  11. "title": "New TW Projec API",
  12. "owner_id": "dsdssdsd445d",
  13. "description": "Testin API",
  14. "status": "unactiveAPI"
  15. },
  16. {
  17. "id": "3",
  18. "title": "Projec API",
  19. "owner_id": "dsdssdsd445d",
  20. "description": "Testin",
  21. "status": "unactiveAPI"
  22. }
  23. ]

当我试图检索它使用如下-

  1. public interface ProjectSummaryRepository extends CrudRepository<List<ProjectSummary>, String>{}
  2. //within main method
  3. Optional<List<ProjectSummary>> summaries = projectSummaryRepo.findById(COUCHBASE_DOCUMENT_ID);

我有个例外说-
java.lang.classcastexception:org.springframework.data.couchbase.core.mapping.couchbaselist不能转换为org.springframework.data.couchbase.core.mapping.couchbasedocument
我对文档类的注解如下-

  1. @Document
  2. public class ProjectSummary implements Serializable {
  3. private static final long serialVersionUID = 1L;
  4. @Id
  5. private String id;
  6. @Field
  7. private String title;
  8. @Field
  9. private String owner_id;
  10. @Field
  11. private String status;
  12. @Field
  13. private String description;
  14. //getters and setters
  15. }
unguejic

unguejic1#

在这种情况下不能使用findbyid。您必须使用springdata dsl来查询您的数据:

  1. public interface ProjectSummaryRepository extends CrudRepository<List<ProjectSummary>, String> {
  2. //using standard Spring Data DSL
  3. List<ProjectSummary> findByTitleAndStatus(String title, String status)
  4. //complex query using N1QL syntax
  5. @Query("#{#n1ql.selectEntity} where #{#n1ql.filter} and status = $1 and ( title = $2 or owner_id = $3)")
  6. List<ProjectSummary> findWithSomeComplexQuery(String status, String title, String owner_id)
  7. }

之后,您可以简单地在代码中调用这些方法;

  1. List<ProjectSummary> sumaries = projectSummaryRepo.findByTitleAndStatus("someTitle", "someStatus")
  2. List<ProjectSummary> sumaries2 = projectSummaryRepo.findWithSomeComplexQuery("someStatus", "someTitle", "owner123" )

相关问题