查询之间的mongo jpa

时间:2019-10-15 06:45:48

标签: java spring mongodb jpa

我正在使用spring jpa与mongo数据库集成。我有一个带有Instance字段的简单mongo文档。在我的存储库中,我尝试过类似

findByInstantBetween(Instant start, Instant end, Pageable pageable);

我有一个简单的弹簧单元测试(使用弹簧流道和正常的弹簧环境运行),如下所示:

import static org.assertj.core.api.Assertions.assertThat;

...


@Test
public void testSearchByInstantBetween() {
    // insert a document before the date range to test, should not be retrieved by query
    MyDocument doc = new MyDocument();
    doc.setInstant(Instant.now());
    doc= docRepository.insert(doc);

    // insert a document with the start instant, should be retrieved
    doc.setId(null);
    Instant start = Instant.now();
    doc.setInstant(start);
    doc = docRepository.insert(doc);

    // insert a document with the end instant, should be retrieved
    doc.setId(null);
    Instant end = Instant.now();
    doc.setInstant(end);
    doc = docRepository.insert(doc);

    // insert a document after the end instant, should not be retrieved
    doc.setId(null);
    doc.setInstant(Instant.now());
    doc = docRepository.insert(doc);

    // check that 4 documents have been inserted
    assertThat(docRepository.findAll()).hasSize(4);

    Pageable pageable = PageRequest.of(0, 5);

    // run between query, expected size is 2
    Page<MyDocument> docs = docRepository.findByInstantBetween(start, end, pageable);
    assertThat(docs.getContent()).hasSize(2); // <-- this fails with expected 2, found 0
}

我还尝试了如下更改查询方法

findByInstantGreaterThanEqualAndInstantLessThanEqual(Instant start, Instant end, Pageable pageable);

使用这种方法运行测试时,我得到

org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the com.mongodb.BasicDocument, you can't add a second 'instant' expression specified as 'instant: Document{{$lte=2019-10-15T06:28:43.508Z}}'. Criteria already contains 'instant : Document{{$gte=2019-10-15T06:28:43.505Z}}'.

有人遇到过这种问题吗?

2 个答案:

答案 0 :(得分:1)

Between查询方法运行正常。我不知道它是排他性的,所以因为我只有一个包含两个元素(分别为startend Instant的测试用例,所以查询在(和不包括)那些和找到0个元素。

当我在Instantstart的中间添加另一个带有end的元素时,我期望3,但它返回1。

为了使查询具有包容性,我将其注释如下

@org.springframework.data.mongodb.repository.Query("{ instant: {$gte: ?0, $lte: ?1}}")

其中?0?1分别与startend参数相对应。

希望这可以帮助其他人。

答案 1 :(得分:0)

使用下面的示例查询来查找大于或等于且小于或等于的东西。

@Query("{instant : {$gte : ?0, $lte : ?1}}")
 findUsingQ(Instant start, Instant end, Pageable pageable);