SpringBoot整合之SpringBoot整合MongoDB的詳細(xì)步驟
MongoDB 是一個(gè)基于分布式文件存儲(chǔ)的數(shù)據(jù)庫。由 C++ 語言編寫。旨在為 WEB 應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲(chǔ)解決方案。
MongoDB 是一個(gè)介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫的。本文介紹SpringBoot整合之SpringBoot整合MongoDB的步驟。
一、創(chuàng)建項(xiàng)目,選擇依賴
僅選擇Spring Web、Spring Data MongoDB即可



二、引入相關(guān)依賴(非必要)
這里只是為了實(shí)體類的創(chuàng)建方便而引入lombok
<!-- 引入lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
三、如果是第一次使用MongoDB,首先先創(chuàng)建用戶
> use admin
switched to db admin
> db.createUser({user:"zlfeng", pwd:"123456", roles:[{role:"readWriteAnyDatabase", db:"admin"}]});
Successfully added user: {
"user" : "zlfeng",
"roles" : [
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
]
}
MongoDB權(quán)限介紹
| 權(quán)限 | 說明 |
|---|---|
| read | 允許用戶讀取指定數(shù)據(jù)庫 |
| readWrite | 允許用戶讀寫指定數(shù)據(jù)庫 |
| dbAdmin | 允許用戶在指定數(shù)據(jù)庫中執(zhí)行管理函數(shù),如索引創(chuàng)建、刪除、查看統(tǒng)計(jì)或訪問system.profile |
| userAdmin | 允許用戶向system.users集合寫入,可以在指定數(shù)據(jù)庫中創(chuàng)建、刪除和管理用戶 |
| clusterAdmin | 必須在admin數(shù)據(jù)庫中定義,賦予用戶所有分片和復(fù)制集相關(guān)函數(shù)的管理權(quán)限 |
| readAnyDatabase | 必須在admin數(shù)據(jù)庫中定義,賦予用戶所有數(shù)據(jù)庫的讀權(quán)限 |
| readWriteAnyDatabase | 必須在admin數(shù)據(jù)庫中定義,賦予用戶所有數(shù)據(jù)庫的讀寫權(quán)限 |
| userAdminAnyDatabase | 必須在admin數(shù)據(jù)庫中定義,賦予用戶所有數(shù)據(jù)庫的userAdmin權(quán)限 |
| dbAdminAnyDatabase | 必須在admin數(shù)據(jù)庫中定義,賦予用戶所有數(shù)據(jù)庫的dbAdmin權(quán)限 |
| root | 必須在admin數(shù)據(jù)庫中定義,超級(jí)賬號(hào),超級(jí)權(quán)限 |
四、定義核心配置文件
# 登錄用戶所在的數(shù)據(jù)庫 spring.data.mongodb.authentication-database=admin # 數(shù)據(jù)庫的ip地址 spring.data.mongodb.host=192.168.133.142 # MongoDB端口號(hào) spring.data.mongodb.port=27017 # 用戶賬號(hào) spring.data.mongodb.username=zlfeng # 用戶密碼 spring.data.mongodb.password=123456 # 指定使用的數(shù)據(jù)庫 # 不必預(yù)先創(chuàng)建,不存在該數(shù)據(jù)庫會(huì)自動(dòng)創(chuàng)建 spring.data.mongodb.database=db_student
五、創(chuàng)建實(shí)體類
package cn.byuan.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import java.io.Serializable;
import java.util.Date;
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Data
public class Student implements Serializable {
@Id// 必須指定id列
private String studentId;
private String studentName;
private Integer studentAge;
private Double studentScore;
private Date studentBirthday;
}
六、創(chuàng)建dao層,這里的dao層有兩種寫法
(一)dao層寫法一
1. 編碼部分
package cn.byuan.dao;
import cn.byuan.entity.Student;
import org.springframework.data.mongodb.repository.MongoRepository;
/*
* dao層寫法一
* 這里的用法其實(shí)和SpringDataJPA相似, 可根據(jù)需要來自定義方法
*
* 這種寫法不需要寫實(shí)現(xiàn)類
*
* MongoRepository<行對(duì)應(yīng)的對(duì)象類型, 主鍵列類型>
* */
public interface StudentDaoTypeOne extends MongoRepository<Student, String> {
// 可根據(jù)需求自己定義方法, 無需對(duì)方法進(jìn)行實(shí)現(xiàn)
Student getAllByStudentName(String studentName);
}

2.測試部分
在進(jìn)行測試之前,我們先查詢一下數(shù)據(jù)庫,此時(shí)不存在db_student的庫

開始測試
package cn.byuan;
import cn.byuan.dao.StudentDaoTypeOne;
import cn.byuan.entity.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.List;
@SpringBootTest
class StudentDaoTypeOneTests {
@Autowired
private StudentDaoTypeOne studentDaoTypeOne;
@Test
void addOneStudent(){
// 插入10行
for (Integer count = 0; count < 10; count++) {
Student student = new Student()
.setStudentId("student_"+count) //如果自己不去設(shè)置id則系統(tǒng)會(huì)分配給一個(gè)id
.setStudentName("Godfery"+count)
.setStudentAge(count)
.setStudentScore(98.5-count)
.setStudentBirthday(new Date());
studentDaoTypeOne.save(student);
}
}
@Test
void deleteOneStudentByStudentId(){
// 刪除id為student_0的學(xué)生
studentDaoTypeOne.deleteById("student_0");
}
@Test
void updateOneStudent(){
// 修改姓名為Godfery1的Student年齡為22
Student student = studentDaoTypeOne.getAllByStudentName("Godfery1");
student.setStudentAge(22);
studentDaoTypeOne.save(student);
}
@Test
void getOneStudentByStudentId(){
System.out.println(studentDaoTypeOne.findById("student_1"));
}
@Test
void getAllStudent(){
List<Student> studentList = studentDaoTypeOne.findAll();
studentList.forEach(System.out::println);
}
}

我們先來查看一下數(shù)據(jù)庫

進(jìn)入數(shù)據(jù)庫查看一下數(shù)據(jù)

(二)dao層寫法二
1.編碼部分
接口部分
package cn.byuan.dao;
import cn.byuan.entity.Student;
import java.util.List;
/*
* dao層寫法二
*
* 寫法二需要進(jìn)行實(shí)現(xiàn)
* */
public interface StudentDaoTypeTwo {
// 增加一位學(xué)生
void addOneStudent(Student student);
// 根據(jù)id刪除一位學(xué)生
void deleteOneStudentByStudentId(String studentId);
// 修改一位學(xué)生的信息
void updateOneStudent(Student student);
// 根據(jù)主鍵id獲取一名學(xué)生
Student getOneStudentByStudentId(String studentId);
// 獲取全部學(xué)生
List<Student> getAllStudent();
}
實(shí)現(xiàn)類
package cn.byuan.dao.imp;
import cn.byuan.dao.StudentDaoTypeTwo;
import cn.byuan.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class StudentDaoTypeTwoImp implements StudentDaoTypeTwo {
// 使用MongoTemplate模板類實(shí)現(xiàn)數(shù)據(jù)庫操作
@Autowired
private MongoTemplate mongoTemplate;
// 增加一位學(xué)生
public void addOneStudent(Student student){
mongoTemplate.save(student);
}
// 根據(jù)id刪除一位學(xué)生
public void deleteOneStudentByStudentId(String studentId){
Student student = mongoTemplate.findById(studentId, Student.class);
if(student != null){
mongoTemplate.remove(student);
}
}
// 修改一位學(xué)生的信息
public void updateOneStudent(Student student){
mongoTemplate.save(student);
}
// 根據(jù)主鍵id獲取一名學(xué)生
public Student getOneStudentByStudentId(String studentId){
return mongoTemplate.findById(studentId, Student.class);
}
// 獲取全部學(xué)生
public List<Student> getAllStudent(){
return mongoTemplate.findAll(Student.class);
}
}
2.測試部分
package cn.byuan;
import cn.byuan.dao.StudentDaoTypeOne;
import cn.byuan.dao.StudentDaoTypeTwo;
import cn.byuan.entity.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.List;
@SpringBootTest
class StudentDaoTypeTwoTests {
@Autowired
private StudentDaoTypeTwo studentDaoTypeTwo;
@Test
void addOneStudent(){
// 插入10行
for (Integer count = 0; count < 10; count++) {
Student student = new Student()
.setStudentId("study_"+count) //如果自己不去設(shè)置id則系統(tǒng)會(huì)分配給一個(gè)id
.setStudentName("Echo"+count)
.setStudentAge(count)
.setStudentScore(98.5-count)
.setStudentBirthday(new Date());
studentDaoTypeTwo.addOneStudent(student);
}
}
@Test
void deleteOneStudentByStudentId(){
// 刪除id為study_0的學(xué)生
studentDaoTypeTwo.deleteOneStudentByStudentId("study_0");
}
@Test
void updateOneStudent(){
// 修改id為study_1的Student年齡為21
Student student = studentDaoTypeTwo.getOneStudentByStudentId("study_1");
student.setStudentAge(21);
studentDaoTypeTwo.updateOneStudent(student);
}
@Test
void getOneStudentByStudentId(){
System.out.println(studentDaoTypeTwo.getOneStudentByStudentId("study_1"));
}
@Test
void getAllStudent(){
List<Student> studentList = studentDaoTypeTwo.getAllStudent();
studentList.forEach(System.out::println);
}
}

進(jìn)入數(shù)據(jù)庫查看一下數(shù)據(jù)

源碼地址:https://github.com/byuan98/springboot-integration/tree/master/test008_springboot_mongodb
到此這篇關(guān)于SpringBoot整合之SpringBoot整合MongoDB的詳細(xì)步驟的文章就介紹到這了,更多相關(guān)SpringBoot整合MongoDB內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
到此這篇關(guān)于SpringBoot整合之SpringBoot整合MongoDB的詳細(xì)步驟的文章就介紹到這了,更多相關(guān)SpringBoot整合MongoDB內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中Final關(guān)鍵字的使用技巧及其性能優(yōu)勢詳解
這篇文章主要介紹了Java中Final關(guān)鍵字的使用技巧及其性能優(yōu)勢詳解,Java中的final關(guān)鍵字用于修飾變量、方法和類,可以讓它們在定義后不可更改,從而提高程序的穩(wěn)定性和可靠性,此外,final關(guān)鍵字還有一些使用技巧和性能優(yōu)勢,需要的朋友可以參考下2023-10-10
Elasticsearch Join字段類型簡單快速上手教程
這篇文章主要為大家介紹了Elasticsearch Join字段類型簡單快速上手教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
一文學(xué)會(huì)如何在SpringBoot中使用線程池執(zhí)行定時(shí)任務(wù)
在開發(fā)現(xiàn)代應(yīng)用程序時(shí),定時(shí)任務(wù)是一項(xiàng)常見的需求,SpringBoot提供了一個(gè)強(qiáng)大的定時(shí)任務(wù)框架,可以輕松地執(zhí)行各種定時(shí)任務(wù),結(jié)合線程池的使用,可以更好地管理任務(wù)的執(zhí)行,提高系統(tǒng)的性能和穩(wěn)定性,本文將介紹如何在Spring Boot中使用線程池執(zhí)行定時(shí)任務(wù)2023-06-06

