首先我们创建一个Maven项目。
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.1.1</version> </dependency> </dependencies>
package com.jihu; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.InsertOneResult; import org.bson.Document; import org.bson.conversions.Bson; import static com.mongodb.client.model.Filters.eq; public class QuickStart { public static void main(String[] args) { // 连接本地默认端口的Mongod // MongoClient mongoClient = MongoClients.create() // 连接远程服务的指定端口的Mongod // MongoClient mongoClient = MongoClients.create("mongodb://host1:27017"); // 连接指定端口复制集 // MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet"); // 连接mongos路由: 连接一个 // MongoClient mongoClient = MongoClients.create( "mongodb://localhost:27017" ); // 连接多个mongos路由。 // MongoClient mongoClient = MongoClients.create("mongodb://192.168.131.171:4000,192.168.131.171:4001,192.168.131.171:4002"); // 注意,这里我们配置mongos服务信息即可 MongoClient mongoClient = MongoClients.create("mongodb://192.168.131.171:4000"); //获取数据库 MongoDatabase database = mongoClient.getDatabase("order"); // 获取集合 MongoCollection<Document> productdesc = database.getCollection("accounts"); // 添加数据 // Document doc = new Document("name", "MongoDB") // .append("type", "database") // .append("count", 1) // .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6")) // .append("info", new Document("x", 203).append("y", 102)); // accounts结构:name和 age Document doc = new Document().append("name", "xiaoyixian") .append("age", "23"); InsertOneResult result = productdesc.insertOne(doc); System.out.println(result); // === 查询 // 构建等值查询条件, Filters这个类中定义了很多的静态方法进行过滤 Bson eq = eq("name", "xiaoyixian"); FindIterable<Document> find = productdesc.find(eq); Document first = find.first(); System.out.println(first); } }
此时已经插入和查询成功了。
我们连接到mongs客户端中验证一下:
我们已经完成了java客户端和MongoDB的整合。更多的操作可以去了解详细的API。
官网demo:https://mongodb.github.io/mongo-java-driver/4.1/driver/
官网资料:https://docs.spring.io/spring-data/mongodb/docs/3.1.2/reference/html/#preface
我们首先还是先创建一个SpringBoot项目。
<?xml version="1.0" encoding="UTF-8"?> <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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>springboot-mongo</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
比如连接上述的 mongos, 使用MongoTemplate 进行数据库操作。
package com.jihu.conf; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoTemplate; @Configuration public class AppConfig { public @Bean MongoClient mongoClient() { return MongoClients.create("mongodb://192.168.131.171:4000"); } public @Bean MongoTemplate mongoTemplate() { return new MongoTemplate(mongoClient(), "order"); } }
@SpringBootApplication public class MongoApplication { public static void main(String[] args) { SpringApplication.run(MongoApplication.class, args); } }
package com.jihu.entity; public class Person { private String id; private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getId() { return id; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
这个类实现了Spring的ApplicationRunner接口中的run方法,Spring启动的时候就会执行该方法。
package com.jihu.mongo; import com.jihu.entity.Person; import com.mongodb.client.MongoCollection; import lombok.extern.slf4j.Slf4j; import org.bson.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; import java.util.List; import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; import static org.springframework.data.mongodb.core.query.Update.update; @Component @Slf4j public class ApplicationRunnerTest implements ApplicationRunner { @Autowired private MongoTemplate mongoOps; // spring启动的时候会调用这个方法 @Override public void run(ApplicationArguments applicationArguments) { Person p = new Person("Marco", 34); // 插入文档 mongoOps.insert(p); log.info("Insert: " + p); // 查询文档 p = mongoOps.findById(p.getId(), Person.class); log.info("Found: " + p); // 更新文档 mongoOps.updateFirst(query(where("name").is(p.getName())), update("age", 35), Person.class); p = mongoOps.findOne(query(where("name").is(p.getName())), Person.class); log.info("Updated: " + p); // 删除文档 mongoOps.remove(p); // Check that deletion worked List<Person> people = mongoOps.findAll(Person.class); log.info("Number of people = : " + people.size()); mongoOps.dropCollection(Person.class); } }
从结果可以看到,已经可以成功使用springboot调用mongo了。
mongo支持事务,但是很影响性能!我们一般不会开启事务。