pom.xml
代码语言:javascript
复制
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mongoDB</groupId> <artifactId>mongoDB</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <maven-compiler-plugin-version>3.8.1</maven-compiler-plugin-version> </properties> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.10</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.5.0</version> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.21.0</version> <!-- 使用最新版本 --> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.8.2</version> <scope>test</scope> </dependency> </dependencies> </project>
链接MongoDB Java实现
代码语言:javascript
复制
package mongoDB; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.InsertOneModel; import com.mongodb.client.model.WriteModel; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import org.bson.Document; import org.bson.conversions.Bson; import java.util.ArrayList; import java.util.List; public class MongoDB { // MongoDB服务器的连接URI public static String uri = "mongodb://192.168.31.184:27017"; // 创建MongoClient实例 public static MongoClientURI clientURI = new MongoClientURI(uri); public MongoClient mongoClient = new MongoClient(clientURI); public MongoDatabase connect(String dbname) { // 连接成功,可以进行数据库操作 System.out.println("Connected to MongoDB"); // 获取数据库实例 MongoDatabase database = mongoClient.getDatabase(dbname); return database; } public void disconnect() { // 关闭连接 this.mongoClient.close(); } public MongoCollectiongetCollection(MongoDatabase database,String mycollection) { // 获取集合实例 MongoCollection collection = database.getCollection(mycollection); return collection; } public void insertOneDocument(String key1,String value1,String key2,int value2,MongoCollectioncollection) { // 插入单条文档 Document document = new Document(key1, value1) .append(key2, value2); collection.insertOne(document); } public void insertManyDocument(String[][] values,MongoCollectioncollection) { // 创建多个文档列表 List documents = new ArrayList<>(); for(int i=0;i documents.add(new Document("name", values[i][0]).append("age", Integer.parseInt(values[i][1]))); } // 创建插入模型列表 List <WriteModel> insertManyModels = new ArrayList<>();</WriteModel documents.forEach(doc -> insertManyModels.add(new InsertOneModel<>(doc))); // 插入多条记录 collection.insertMany(documents); } public MongoCursorsearchDocument(String key,String value,MongoCollectioncollection) { // 根据关键字查询文档 Document query = new Document(key, value); MongoCursor cursor = collection.find(query).iterator(); return cursor; } public FindIterablefuzzyQuery(String key,String value,MongoCollectioncollection) { Bson eq = Filters.regex(key, value); FindIterableiterable = collection.find(eq); return iterable; } public FindIterableViewAllDocument(MongoCollectioncollection) { //显示所有的文档 FindIterable iterable = collection.find(); return iterable; } public UpdateResult updateOneDocument(String key_filter,String value_filter,String key_update,String value_update,MongoCollectioncollection) { // 更新一条文档 Document filter = new Document(key_filter,value_filter); Document update = new Document("$set", new Document(key_update,value_update)); return collection.updateOne(filter, update); } public UpdateResult updateOneDocument(String key_filter,String value_filter,String key_update,int value_update,MongoCollectioncollection) { // 更新一条文档 Document filter = new Document(key_filter,value_filter); Document update = new Document("$set", new Document(key_update,value_update)); return collection.updateOne(filter, update); } public UpdateResult updateManyDocument(String key_filter,String value_filter,String key_update,int value_update,MongoCollectioncollection) { // 更新多条文档 Document filter = new Document(key_filter,value_filter); Document update = new Document("$set", new Document(key_update,value_update)); return collection.updateMany(filter, update); } public UpdateResult updateManyDocument(String key_filter,int value_filter,String key_update,int value_update,MongoCollectioncollection) { // 更新多条文档 Document filter = new Document(key_filter,value_filter); Document update = new Document("$set", new Document(key_update,value_update)); return collection.updateMany(filter, update); } public DeleteResult deleteManyDocument(String key,String value,MongoCollectioncollection) { // 删除多条文档 Document filter = new Document(key, value); return collection.deleteOne(filter); } public DeleteResult deleteManyDocument(String key,int value,MongoCollectioncollection) { // 删除多条文档 Document filter = new Document(key, value); return collection.deleteMany(filter); } public DeleteResult deleteOneDocument(String key,String value,MongoCollectioncollection) { // 删除一条文档 Document filter = new Document(key, value); return collection.deleteOne(filter); } public DeleteResult deleteOneDocument(String key,int value,MongoCollectioncollection) { // 删除一条文档 Document filter = new Document(key, value); return collection.deleteOne(filter); } }
JUnit5 测试代码testMongoDB.java
代码语言:javascript
复制
package mongoDB; import org.bson.Document; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; public class testMongoDB { static MongoDB mdb = new MongoDB(); static MongoCollectioncollection = null; static String key1 = "name"; static String value1 = "Jone"; static String key2 = "age"; static int value2 = 35; static String[][] values = {{"Alice","25"},{"Bob","25"},{"Jerry","25"}}; @BeforeAll @DisplayName("运行所有测试用例前连接数据库") public static void startALL(){ MongoDatabase database = mdb.connect("admin"); collection = mdb.getCollection(database,"person"); } @AfterAll @DisplayName("运行所有测试用例后断开数据库") public static void endAll(){ mdb.disconnect(); } @BeforeEach @DisplayName("每条用例开始时执行") public void start(){ mdb.insertOneDocument(key1,value1,key2,value2,collection); mdb.insertManyDocument(values,collection); } @AfterEach @DisplayName("每条用例结束时执行") public void end(){ mdb.deleteOneDocument(key1,value1,collection); mdb.deleteManyDocument("age",25,collection); } @Test @DisplayName("测试显示所有的记录") public void testViewAllDocument() { boolean judge=false; FindIterableiterable=mdb.ViewAllDocument(collection); for (Document document : iterable) { assertThat(document.toJson().matches("\"$oid\":^[A-Za-z0-9]+$")); assertThat(document.toJson().matches("\"name\":^[A-Za-z]+$")); assertThat(document.toJson().matches("\"age\":\\d+")); judge = true; } Assertions.assertTrue(judge); } @Test @DisplayName("测试模糊查询") public void testFuzzyQuery() { boolean judge=false; String key = "name"; String value ="J"; FindIterableiterable = mdb.fuzzyQuery(key, value,collection); for (Document document : iterable) { assertThat(document.toJson().matches("\"$oid\":^[A-Za-z0-9]+$")); assertThat(document.toJson().matches("\"name\": \"Q")); assertThat(document.toJson().matches("\"age\":\\d+")); judge = true; } Assertions.assertTrue(judge); } @Test @DisplayName("测试setUp()函数中插入的一条数据是否成功") public void testInsertOneDocument() { judgeDataInDB(key1,value1); } @Test @DisplayName("测试setUp()函数中插入的多条数据是否成功") public void testInsertManyDocument() { for (int i = 0;i < 3 ;i++) { judgeDataInDB(key1,values[i][0]); } } @Test @DisplayName("测试修改一条数据是否成功") public void testUpdateOneDocument() { String key_filter = "name"; String value_filter ="Alice"; String key_update = "age"; int value_update = 25; UpdateResult updateOne = mdb.updateOneDocument(key_filter,value_filter,key_update,value_update,collection); assertThat(String.valueOf(updateOne).matches("matchedCount=1, modifiedCount=1")); } @Test @DisplayName("测试修改多条数据是否成功") public void testUpdateManyDocument() { String key_filter = "age"; int value_filter =25; String key_update = "age"; int value_update = 30; UpdateResult updateOne = mdb.updateManyDocument(key_filter,value_filter,key_update,value_update,collection); assertThat(String.valueOf(updateOne).matches("matchedCount=2, modifiedCount=2")); } @Test @DisplayName("测试删除一条数据是否成功") public void testDeleteOneDocument() { String key_filter = "name"; String value_filter ="Alice"; DeleteResult deleteOne = mdb.deleteOneDocument(key_filter,value_filter,collection); assertThat(String.valueOf(deleteOne).matches("matchedCount=1, modifiedCount=1")); } @Test @DisplayName("测试删除多条数据是否成功") public void testDeleteManyDocument() { String key_filter = "age"; int value_filter =25; DeleteResult deleteOne = mdb.deleteManyDocument(key_filter,value_filter,collection); assertThat(String.valueOf(deleteOne).matches("matchedCount=2, modifiedCount=2")); } //验证数据是否在数据库中 public void judgeDataInDB(String key_update,String value_update) { MongoCursorcursor=mdb.searchDocument(key_update,String.valueOf(value_update),collection); while (cursor.hasNext()) { Document result = cursor.next(); assertThat(result.toJson().matches("\""+key_update+"\":\""+String.valueOf(value_update)+"\"")); } } }