1.MongoDB的下载和启动
①下载MongoDB
MongoDB的官网地址是https://www.mongodb.com,进入官网首页,点击右上角的 ,进入下载页:这里选择下载红色框中的社区版软件,依然是使用Windows版本做演示,直接点击DOWNLOAD(msi),得到安装文件mongodb-win32-x86_64-2008plus-ssl-3.4.10-signed.msi。
此外,也可以选择从下面地址中下载Windows版本的MongoDB:http://dl.mongodb.org/dl/win32;相应的Linux版本下载地址为:http://dl.mongodb.org/dl/linux;OSX版本下载地址为:http://dl.mongodb.org/dl/osx。
②安装MongoDB
运行下载得到的MongoDB文件mongodb-win32-x86_64-2008plus-ssl-3.4.10-signed.msi,这里选择了自定义安装,安装路径为D:\soft\MongoDB\Server\3.4。安装完成后进入该文件夹,可看到文件夹内结构如下:
在该文件夹内新建文件夹data,然后在data中新建文件夹db,用来存放接下来的数据文件。
③配置环境变量
新增环境变量MONGODB_HOME,变量值为MongoDB的安装路径D:\soft\MongoDB\Server\3.4;在Path变量中追加MongoDB的配置%MONGODB_HOME%\bin。④启动MongoDB
启动命令行窗口,执行如下命令:mongod -dbpath "D:\soft\MongoDB\Server\3.4\data\db",执行结果如下:此时即已开启MongoDB的服务端。
如果不想每次启动MongoDB服务时都要打开命令窗口,也可以创建一个.bat文件,文件名可定为MongoDB-startup.bat,文件内容如下:
@echo 启动MongoDB
set dbpath="D:\soft\MongoDB\Server\3.4\data\db"
mongod -dbpath %dbpath%
@pause
使用MongoDB-startup.bat重新启动MongoDB服务,启动效果与上述命令窗口一样。由于已经在环境变量中配置了MongoDB,故此启动文件的存放位置没有硬性要求。
⑤MongoDB客户端
在MongoDB服务启动的情况下,运行D:\soft\MongoDB\Server\3.4\bin下的可执行文件mongo.exe,即可开启MongoDB的客户端,这里输入命令show dbs用以查询MongoDB中的所有数据库,其结果如下:可见此时存在两个数据库:admin以及local。
为了观察方便,也可以使用MongoDB的数据库管理软件,本文使用了robomongo,下载地址为https://robomongo.org/,当前最新版本支持MongoDB3.4,可以下载使用便携式版本robo3t-1.1.1-windows-x86_64-c93c6b0.zip。解压后启动客户端,数据库连接地址配置如下:
进入数据库,查看数据库,结果如下:
可见此时存在两个数据库:admin以及local。
2.MongoDB参数配置
①配置pom.xml
Spring Boot中使用MongoDB,需要在pom.xml中配置如下依赖:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
②配置数据源参数
Spring Boot中MongoDB的配置项源码在org.springframework.boot.autoconfigure.mongo.MongoProperties中,其基本结构如下:@ConfigurationProperties(prefix = "spring.data.mongodb")
public class MongoProperties {
// Default port used when the configured port is {@code null}.
public static final int DEFAULT_PORT = 27017;
public static final String DEFAULT_URI = "mongodb://localhost/test";
// Mongo server host. Cannot be set with uri.
private String host;
// Mongo server port. Cannot be set with uri.
private Integer port = null;
// Mongo database URI. Cannot be set with host, port and credentials.
private String uri;
// Database name.
private String database;
// Authentication database name.
private String authenticationDatabase;
// GridFS database name.
private String gridFsDatabase;
// Login user of the mongo server. Cannot be set with uri.
private String username;
// Login password of the mongo server. Cannot be set with uri.
private char[] password;
// Fully qualified name of the FieldNamingStrategy to use.
private Class<?> fieldNamingStrategy;
}
由以上源码可知,MongoDB配置参数的前缀是spring.data.mongodb;并且,默认host是localhost,默认端口号是27017,默认使用的数据库是test;同时,由字段说明可知,uri参数与host、port、database、username、password是互斥的,配置参数时,二者只能选择其一。常用的配置如下:
## MongoDB
# mongodb服务器地址(默认为localhost)
#spring.data.mongodb.host=127.0.0.1
# mongodb服务器连接端口(默认为27017)
#spring.data.mongodb.port=27017
# mongodb数据库(默认为test)
#spring.data.mongodb.database=student
# mongodb用户名
#spring.data.mongodb.username=
# mongodb密码
#spring.data.mongodb.password=
# URI,格式:mongodb://username:password@host:port/database
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/student
3.使用MongoDB存储数据
①场景设计
为了方便展示使用MongoDB存储数据,先来设定一个使用场景,如下:现需要添加学生信息,学生的信息包括姓名、年龄,此外还有学生考试的课程名称及该课程的得分情况。②代码实现
首先,创建一个考试的实体类Exam:package net.xxpsw.demo.springboot.data.mongodb.entity;
public class Exam {
/** 课程 */
private String course;
/** 得分 */
private Integer score;
public Exam() {
super();
}
public Exam(String course, Integer score) {
super();
this.course = course;
this.score = score;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
其次,创建一个学生的实体类Student:
package net.xxpsw.demo.springboot.data.mongodb.entity;
import java.util.Collection;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "student_exams")
public class Student {
@Id
private String id;
private String name;
private Integer age;
private Collection<Exam> exams;
public Student() {
super();
}
public Student(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Collection<Exam> getExams() {
return exams;
}
public void setExams(Collection<Exam> exams) {
this.exams = exams;
}
}
在学生实体类Student中,@Document注解映射了模型和MongoDB的文档,其中collection属性表明了MongoDB中使用的文档名称;而@Id注解表明了该属性为文档的Id。
然后,创建MongoDB的数据操作接口StudentExamRepository:
package net.xxpsw.demo.springboot.data.mongodb.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import net.xxpsw.demo.springboot.data.mongodb.entity.Student;
public interface StudentExamRepository extends MongoRepository<Student, String> {}
最后,创建控制类MongoDBController:
package net.xxpsw.demo.springboot.data.mongodb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.xxpsw.demo.springboot.data.mongodb.dao.StudentExamRepository;
@RestController
@RequestMapping("mongo")
public class MongoDBController {
Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private StudentExamRepository studentExamRepository;
}
③数据存储
在控制类MongoDBController中添加如下方法: /**
* @Description: 使用MongoDB保存数据
* @return Student
*/
@RequestMapping("save")
public Student save() {
Student student = new Student("Jack", 26);
Collection<Exam> exams = new LinkedHashSet<Exam>();
exams.add(new Exam("高等代数", 90));
exams.add(new Exam("线性几何", 88));
exams.add(new Exam("大学英语", 95));
student.setExams(exams);
return studentExamRepository.save(student);
}
启动Spring Boot,于浏览器中访问http://localhost:8088/demo/mongo/save,页面返回如下数据:
此时使用MongoDB客户端查看,可以看到数据库中已经新增了一个库student,并且该库中存在一个文档student_exams,查看该文档,结构如下:
此时数据即已保存至MongoDB中。除了录入的属性外,student_exams文档中还包含属性_class和_id,其中_class为与MongoDB文档映射的实体类,而_id的生成基于当前时间戳,源码包路径org.bson.types.ObjectId。
4.读取MongoDB中的数据
①使用Example查询
查询MongoDB数据可以使用Example,Example的包路径是org.springframework.data.domain.Example;在控制类MongoDBController中添加如下方法: /**
* @Description: 使用Example查询MongoDB数据
* @param name 姓名
* @param age 年龄
* @return Student
*/
@RequestMapping("findByExample")
public Student findByExample(String name, Integer age) {
Student student = new Student(name, age);
return studentExamRepository.findOne(Example.of(student));
}
在浏览器中访问http://localhost:8088/demo/mongo/findByExample?name=Jack&age=26,页面结果如下:
这里展示的信息即为之前保存在MongoDB中的数据。
②通过属性查询
通过实体类Student中的属性也可以查询MongoDB的数据,在数据访问接口StudentExamRepository中添加如下方法:public List<Student> findByName(String name);
在控制类MongoDBController中添加如下方法:
/**
* @Description: 通过属性查询MongoDB数据
* @param name 姓名
* @return List<Student>
*/
@RequestMapping("findByProperty")
public List<Student> findByProperty(String name) {
return studentExamRepository.findByName(name);
}
在浏览器中访问http://localhost:8088/demo/mongo/findByProperty?name=Jack,结果如下:
③使用查询语句查询
查询MongoDB的数据还可以使用查询语句,在数据访问接口StudentExamRepository中添加如下方法: @Query("{'age':?0}")
public Student withQueryFindByAge(Integer age);
在控制类MongoDBController中添加如下方法:
/**
* @Description: 使用查询语句查询MongoDB数据
* @param age 年龄
* @return Student
*/
@RequestMapping("findWithQuery")
public Student findWithQuery(Integer age) {
return studentExamRepository.withQueryFindByAge(age);
}
于浏览器中访问http://localhost:8088/demo/mongo/findWithQuery?age=26,得到结果如下:
使用以上方式均可实现对MongoDB数据的查询。