开发环境:
windows 7
idea
windows64 mongodb 如果没安装运行 点这里
navicat for mongodb 下面介绍用的是这个图形工具,命令行客户端或其他图形工具都是可以的,如果需要这个 点这里
创建mongodb测试的数据
首先连接mongodb ,然后新建mongodb数据库 testdb
打开数据库testdb,然后点击新建查询,在查询栏中 新建数据库testdb的集合user 并添加一条记录,点击运行
查询栏内容:
db.createCollection('user')
db.user.insert({
account: '110',
password: '123456',
phone: '188xxxxxxxx',
name: 'zhangsan'
})
springboot mongodb测试源码
springboot 项目 mongodb_demo 的目录结构
pom.xml
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>mongodb_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mongodb_demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置文件 application.properties
server.port=8086
spring.data.mongodb.testdb.database=testdb
spring.data.mongodb.testdb.host=localhost
spring.data.mongodb.testdb.username=root
spring.data.mongodb.testdb.password=123456
spring.data.mongodb.testdb.port=27017
testdb数据库的配置类 TestdbMongoConfiguration
package com.example.mongodb_demo.config;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import java.util.ArrayList;
import java.util.List;
@Configuration
//读取配置文件中spring.data.mongodb.testdb 开头的属性如database,通过反射调用setDatabase()保存从配置文件中读取的database值
//需要maven依赖 spring-boot-configuration-processor
@ConfigurationProperties(prefix = "spring.data.mongodb.testdb")
public class TestdbMongoConfiguration {
// MongoDB Properties
private String host, database, username, password;
private int port;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(new MongoClient(host, port), database);
// //注意:上面连接mongodb的工厂没有用到账号密码认证,如需账号密码认证,下面写法
// ServerAddress serverAddress = new ServerAddress(host, port);
// List<MongoCredential> mongoCredentialList = new ArrayList<>();
// mongoCredentialList.add(MongoCredential.createCredential(username, database, password.toCharArray()));
// return new SimpleMongoDbFactory(new MongoClient(serverAddress, mongoCredentialList), database);
}
//第一个数据库 默认作为主数据库 需要添加注解 @Primary ,后面的数据库不需要这个注解
@Primary
@Bean(name = "testdbMongoTemplate")
public MongoTemplate getMongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}
User
package com.example.mongodb_demo.pojo;
import org.springframework.data.mongodb.core.mapping.Document;
//user 是mongodb数据库中集合名
@Document(collection="user")
public class User {
private String account;
private String password;
private String name;
private String phone;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"account='" + account + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
web测试类 TestController
package com.example.mongodb_demo.controller;
import com.example.mongodb_demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
@Qualifier(value = "testdbMongoTemplate")
protected MongoTemplate mongoTemplate;
@RequestMapping("/test")
public String test(){
Query query = new Query();
query.addCriteria(Criteria.where("name").is("zhangsan"));
User user = mongoTemplate.findOne(query, User.class);
return user.toString();
}
}
启动类 MongodbDemoApplication
package com.example.mongodb_demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MongodbDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MongodbDemoApplication.class, args);
}
}
测试
浏览器输入 127.0.0.1:8086/test
源码
链接:https://pan.baidu.com/s/14xFDYg4qK05XKtSozwHfFw
提取码:aat9