提供对 Spring Data Mongo 存储库的限制

Jas*_*eck 2 java mongodb spring-data spring-data-mongodb

使用最新的 Spring Data Mongo(撰写本文时为 2.1.1),如何指定获取“自定义”查询方法的第一条记录?下面是一个例子:

@Query(value="{name: ?0, approval: {'$ne': null}}",
        sort="{'approval.approvedDate': -1}",
        fields = "{ _id: 1 }")
List<Item> getLatestApprovedIdByName(String name, Pageable pageable);

/**
 * Finds the id of the most recently approved document with the given name.
 */
default Item getLatestApprovedIdByName(String name) {
    return getLatestApprovedIdByName(name, PageRequest.of(0, 1)).stream().findFirst().orElse(null);
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我可以只使用 String 参数来注释 getLatestApprvedIdByName。org.springframework.data.mongodb.repository.Query注释上似乎没有限制字段。这看起来很奇怪,因为我可以模拟命名方法所做的一切,除了“findFirst”。如果没有 Pageable,我得到IncorrectResultSizeDataAccessException,并且返回 aList是不可接受的,因为我不想浪费时间返回任意大的结果,加上需要处理 0 或 1 个项目的可能性的复杂代码。

Syn*_*ync 6

由于您的查询返回多个文档,因此无法Item直接返回单个文档。

使用 Stream

// Repository
@Query(value="{name: ?0, approval: {'$ne': null}}",
        sort="{'approval.approvedDate': -1}",
        fields = "{ _id: 1 }")
Stream<Item> getLatestApprovedIdByName(String name);

// Service
default Item getLatestApprovedIdByName(String name) {
    return getLatestApprovedIdByName(name).stream().findFirst().orElse(null);
}
Run Code Online (Sandbox Code Playgroud)

由于Stream工作方式,您将只获取第一个查询结果而不是整个结果集。有关更多信息,请参阅文档

使用PagePageable

// Repository
@Query(value = "{name: ?0, approval: {'$ne': null}}", fields = "{ _id: 1 }")
Page<Item> getLatestApprovedIdByName(String name, Pageable pageable);

// Service
default Item getLatestApprovedIdByName(String name) {
    PageRequest request = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "approval.approvedDate"));
    return getLatestApprovedIdByName(name, request).getContent().get(0);
}
Run Code Online (Sandbox Code Playgroud)

通过使用PageRequest,您可以指定所需的结果数量以及指定排序顺序。基于这个答案