MongoRepository 删除方法

MongoRepository Delete Method

大家下午好!

我花了最后一个小时从我的 mongo“testCollection”中删除单个文档。我想使用 MongoRepository delete / deleteAll 方法。但是,它不会删除文档。无论我 运行 测试 class 方法多少次,它都会持续存在。没有报错,用户对数据库有读写权限。我可以 运行 mongo 命令删除新创建的测试文档。

我已阅读有关使用 mongo 模板并创建它以执行删除的信息。我很乐意这样做,但我宁愿让它尽可能简单。

import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoId;

@Data
@Document(collection = "testCollection")
public class TestClass {
    @MongoId
    private String id;

    private String name;

    public TestClass(String name) {
        this.name = name;
    }
}

测试ClassMongo存储库接口

import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;

public interface TestClassRepository extends MongoRepository<TestClass, String> {
    public List<TestClass> findAllByName(String name);
    public void deleteAllByIdIn(List<TestClass> list);
}

测试方法

import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@TestPropertySource(value = {"classpath:application.properties"})
@AutoConfigureMockMvc
public class testClassTest {
    @Autowired
    private TestClassRepository testClassRepository;

    @Test
    public void crudTest() {

        TestClass testObj = new TestClass("Test");
        testClassRepository.save(testObj);

        List<TestClass> testClassList = testClassRepository.findAllByName("Test");
        Assert.assertEquals(1, testClassList.size());

        TestClass test = testClassList.get(0);
        testClassRepository.deleteAllByIdIn(testClassList);

        // Fails this assertion: Found 1, expected 0.
        Assert.assertEquals(0, testClassRepository.findAllByName("Test").size());
    }
}

其他人遇到过类似的问题吗?如果是这样,您是如何解决的?

谢谢!

对原始 post 的补充:

  1. 这是 Mongo 存储库生成的 mongo 查询。看起来它实际上并没有将“remove”mongo 命令添加到查询中。 查询:{ "name" : "Test"},字段:{},排序:{}

幸运的是,我设法解决了这个问题。问题出在我使用的标识符注释类型上。另一个 Whosebug 用户 () 的解释让我重新审视了模型的这一方面。

我将标识符注释从@MongoId 切换为@Id。因为我有 JPA 和 MongoDB 注释,所以我需要确保我从 org.springframework.data.annotation 包中选择了一个,而不是 javax.persistance包.

希望这个解释对其他人有帮助!