下午好,各位程序员!
我花了最后一个小时从我的芒果"testCollection“中删除一个文档。我想使用MongoRepository delete / deleteAll方法。但是,它不会删除文档。不管我运行了多少次测试类方法,它都会持续存在。没有报告错误,而且用户在数据库中具有readWrite权限。我能够运行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;
}
}测试类Mongo接口
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());
}
}其他人也经历过类似的问题吗?如果是的话,你是怎么解决的?
谢谢!
对原员额的增加:
发布于 2021-05-23 12:52:49
幸运的是,我设法解决了这个问题。问题在于我使用的标识符注释的类型。来自另一个堆栈溢出用户(What is use of @MongoId in Spring Data MongoDB over @Id?)的这一解释让我重新审视了模型的这个方面。
我将标识符注释从@MongoId切换到@Id。因为我有JPA和MongoDB注释,所以我需要确保从org.springframework.data.annotation包而不是javax.persistance包中选择一个。
希望这个解释能帮到别人!
https://stackoverflow.com/questions/67653261
复制相似问题