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

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

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

[
    {
        "id": "1",
        "title": "New API",
        "owner_id": "dsdssdsd445d",
        "description": "Yh A Testin API",
        "status": "unactiveAPI"
    },
    {
        "id": "2",
        "title": "New TW Projec API",
        "owner_id": "dsdssdsd445d",
        "description": "Testin API",
        "status": "unactiveAPI"
    },
    {
        "id": "3",
        "title": "Projec API",
        "owner_id": "dsdssdsd445d",
        "description": "Testin",
        "status": "unactiveAPI"
    }
]

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

public interface ProjectSummaryRepository extends CrudRepository<List<ProjectSummary>, String>{}

//within main method
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
我对文档类的注解如下-

@Document
public class ProjectSummary implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    private String id;
    @Field
    private String title;
    @Field
    private String owner_id;
    @Field
    private String status;
    @Field
    private String description;

    //getters and setters
}
unguejic

unguejic1#

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

public interface ProjectSummaryRepository extends CrudRepository<List<ProjectSummary>, String> {

   //using standard Spring Data DSL
   List<ProjectSummary> findByTitleAndStatus(String title, String status)

   //complex query using N1QL syntax
   @Query("#{#n1ql.selectEntity} where #{#n1ql.filter} and status = $1 and ( title  = $2 or owner_id = $3)")
   List<ProjectSummary> findWithSomeComplexQuery(String status, String title, String owner_id)
 }

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

List<ProjectSummary> sumaries = projectSummaryRepo.findByTitleAndStatus("someTitle", "someStatus")

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

相关问题