Spring 带有子元素的 CrudRepository 查询?

Spring CrudRepository query with child element?

我有如下的 couchbase 文档

{
  "contentTimestamp": 1470216079085,
  "version": 12,
  "content": [
    {
      "text": "ABC",
      "params": {
        "TYPE": "TEXT"
      }
    }
    ],
  "readers": {
    "u_id_1": 0,
    "u_id_2": 0,
  },
  "contributors": [
    {
      "id": "u_id_1"
    }
  ]
}

文档class

@Document
public class ContentDoc implements Serializable{

    private static final long serialVersionUID = 1L;


    @Id
    private String id;

    @Field
    private Integer version = 12;

    @Field
    private List<Content> content = new ArrayList<>();

    @Field
    private Map<String, Object> readers = new HashMap<>();

    //etc

    //getter setter

}

服务

@Service
public interface ContentDocRepository extends CrudRepository<ContentDoc, String> {

    public List<ContentDoc> findByReadersIn(String reader) throws Exception;

}

测试用例

@RunWith(SpringJUnit4ClassRunner.class)
public class Tests {

    @Autowired
    private ContentDocRepository contentDocRepository;

    @Test
    public void cotentDocRepoTest(){

        List<ContentDoc> contents = contentDocRepository.findByReadersIn("u_id_1");
        Assert.assertNotNull(contents);
        System.out.println(contents)
    }
}

我按照上面的方法编写了代码,但无法检索结果总是空数组列表。

任何人都知道我的代码出了什么问题以及我如何使用子元素执行查询?

在此先感谢。

经过长时间的 RND 和实验我得到了解决方案,

we dont have way to finding child element with method name so we need to do as per my following answer

步骤:

  1. 按照以下内容在 couchbase 中创建自定义视图

视图名称 : findContentByUser

function (doc, meta) {
  
  if(doc._class == "package.model.ContentDoc") {
    for(var i=0; i < doc.contributors.length; i++){
         emit(doc.contributors[i].id, null);
    }
       
  }
}  
  1. Repository : 按照下面的方法使用 impl 方法绑定 viewname 和 designDocument

     @Repository
     public interface ContentDocRepository extends CrudRepository<ContentDoc, String> {
    
        @View(viewName = "findContentByUser", designDocument="dev_content")
        public List<ContentDoc> findByContributors_id(String id);   
    }
    

终于有结果了:)

@Service
public interface ContentDocRepository extends CrudRepository<ContentDoc, String> {

    @View(viewName = "findContentByUser", designDocument="dev_content")
    public List<ContentDoc> findByContributors_id(String id) throws Exception;

}

您不再需要创建视图,只需使用 @N1qlPrimaryIndexed 和 @ViewIndexed 注释,它应该可以工作 out-of-the-box:

@N1qlPrimaryIndexed
@ViewIndexed(designDoc = "building")
public interface BuildingRepository extends 
CouchbasePagingAndSortingRepository<Building, String> {

    List<Building> findByCompanyId(String companyId);

}

我在这里回答了一个非常相似的问题

您可以在这里按照我的教程进行操作: https://blog.couchbase.com/couchbase-spring-boot-spring-data/