Spring Boot 教程

集成 MongoDB

本章节将介绍怎样在 Spring Boot 中集成 MongoDB 非关系数据库。

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似 json 的 bson 格式,因此可以存储比较复杂的数据类型。

MongoDB 最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

准备工作

(1)启动 MongoDB 数据库(MongoDB 版本 mongodb-win32-x86_64-2012plus-4.2.3),命令如下:

mongod --logpath D:/data/log/mongodb.log --dbpath D:/data/db

(2)在 test 数据库中创建 users 集合,且添加4条数据。脚本如下:

db.users.insert([
    {userId:1, name:'张三', sex:'男', age:22},
    {userId:2, name:'李四', sex:'女', age:32},
    {userId:3, name:'王五', sex:'男', age:28},
    {userId:4, name:'赵六', sex:'男', age:26}
])

添加 POM 依赖

在项目的 pom.xml 文件中添加下面依赖配置:

<!-- MongoDB 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

配置 MongoDB

在项目的 application.properties 或 application.yml 文件中添加如下配置信息:

# mongodb config
spring.data.mongodb.database=test
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
#spring.data.mongodb.username=用户名
#spring.data.mongodb.password=密码

映射 MongoDB 的 Document

@Document 注解在实体类上使用,表示该类由 MongoDB 来维护该表。

@Id 注解表示主键,不可重复,自带索引,可以在定义的列名上标注,需要自己生成并维护不重复的约束。如果自己不设置 @Id 主键,MongoDB 会自动生成一个唯一主键,并且插入时效率远高于自己设置主键。在实际业务中不建议自己设置主键,应交给mongo自己生成,自己可以设置一个业务id,如int型字段,用自己设置的业务id来维护相关联的表。

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document("users")
public class UserEntity {
    @Id
    private String id;
    private Long userId;
    private String name;
    private int age;
    private String sex;
    // 忽略 getter 和 setter
}

操作 MongoDB

Spring Boot 提供了 MongoTemplate 便捷类,我们使用该类可以完成对 MongoDB 的操作。代码如下:

import com.hxstrive.springboot.mongodb.demo.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private MongoTemplate mongoTemplate;
    
    public void findAll() {
        List<UserEntity> userEntityList = mongoTemplate.findAll(UserEntity.class);
        System.out.println("用户数:" + userEntityList.size());
        for(UserEntity userEntity : userEntityList) {
            System.out.println(userEntity);
        }
    }
}

调用上面的 findAll() 方法,将输出如下结果:

用户数:4
UserEntity{id=5fc720255f15202e14fa948a, userId=1, name='张三', age=22, sex='男'}
UserEntity{id=5fc720255f15202e14fa948b, userId=2, name='李四', age=32, sex='女'}
UserEntity{id=5fc720255f15202e14fa948c, userId=3, name='王五', age=28, sex='男'}
UserEntity{id=5fc720255f15202e14fa948d, userId=4, name='赵六', age=26, sex='男'}
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号