欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在SpringBoot中使用MongoDB完成數(shù)據(jù)存儲

 更新時間:2023年11月19日 09:48:47   作者:Miaow.Y.Hu  
本文主要介紹了在SpringBoot中如惡化使用MongoDB完成數(shù)據(jù)存儲,接下來這篇我們將圍繞MongoDB進行,MongoDB是一個開源的,面向文檔的NoSQL數(shù)據(jù)庫管理系統(tǒng),使用類似JSON的BSON(二進制JSON)格式來存儲數(shù)據(jù),具有靈活的數(shù)據(jù)模型和強大的查詢功能,需要的朋友可以參考下

我們在開發(fā)中用到的數(shù)據(jù)存儲工具有許多種,我們常見的數(shù)據(jù)存儲工具包括:

關(guān)系性數(shù)據(jù)庫:使用表格來存儲數(shù)據(jù),支持事務(wù)和索引。(如:MySQL,Oracle,SQL Server等)。NoSQL數(shù)據(jù)庫:不使用表格來存儲數(shù)據(jù),而是使用鍵值對、文檔、或者圖形等方式來存儲數(shù)據(jù),適合處理高并發(fā)和大規(guī)模數(shù)據(jù)。(Redis,MongoDB,Cassandra等)文件存儲:將數(shù)據(jù)存儲在本地或者遠程服務(wù)器文件中,常用與存儲較小的文件。(FTP,SFTP,AWS C3等)云存儲:數(shù)據(jù)存儲在云端,方便多人協(xié)作和備份。(Google Drive,Dropbox,OneDriver等)內(nèi)存存儲 :將數(shù)據(jù)存儲在內(nèi)存中,提供快速的讀寫速度,但是不適用存儲持久化數(shù)據(jù)(Redis,Memcache等)。緩存:將數(shù)據(jù)存儲在緩存中,提高訪問速度,減少數(shù)據(jù)庫壓力。(Apc,Memcache,Redis等)隊列:將任務(wù)分發(fā)到不同的隊列中進行處理,提高系統(tǒng)的可靠性和可拓展性。(RabbitMQ,Kafka等)

這篇我們將圍繞MongoDB進行,MongoDB是一個開源的,面向文檔的NoSQL數(shù)據(jù)庫管理系統(tǒng),使用類似JSON的BSON(二進制JSON)格式來存儲數(shù)據(jù),具有靈活的數(shù)據(jù)模型和強大的查詢功能。

與傳統(tǒng)的關(guān)系型數(shù)據(jù)庫不同的是,MongoDB不使用表和行的結(jié)構(gòu),而是使用集合和文檔進行的,一個集合就相當于關(guān)系型數(shù)據(jù)庫里邊的表,一個文檔就相當于表中的一行數(shù)據(jù),每個文檔都是一個鍵值對的集合,可以包含不同類型的數(shù)據(jù)。

MongoDB的特點:

  • 面向文檔:MongoDB使用靈活的文檔模型,可以存儲不同結(jié)構(gòu)的數(shù)據(jù),無需事先定義表結(jié)構(gòu)。
  • 可擴展性:MongoDB支持水平擴展,可以通過添加更多的服務(wù)器來處理大規(guī)模的數(shù)據(jù)和高并發(fā)訪問。
  • 高性能:MongoDB具有快速的讀寫性能,支持索引和復(fù)雜查詢。
  • 強大的查詢語言:MongoDB支持豐富的查詢語言,包括條件查詢、范圍查詢、正則表達式查詢等。
  • 數(shù)據(jù)復(fù)制和故障恢復(fù):MongoDB支持數(shù)據(jù)復(fù)制和自動故障恢復(fù),可以提供高可用性和數(shù)據(jù)安全性。
  • 地理空間索引:MongoDB支持地理空間索引,可以進行地理位置相關(guān)的查詢和分析。
  • 開源和活躍的社區(qū):MongoDB是開源的,擁有龐大的用戶社區(qū)和活躍的開發(fā)者社區(qū)。

首先在我們測試MongoDB之前,我們需要安裝MongoDB,MongoDB下載網(wǎng)站:https://www.mongodb.com/try/download/community

在這里插入圖片描述

之后安裝后,創(chuàng)建一個test數(shù)據(jù)庫:

在這里插入圖片描述

引入相關(guān)依賴:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

在application.properties中配置相關(guān)連接:

spring.data.mongodb.uri=mongodb://localhost:27017/test

server.port=7723

創(chuàng)建一個實體類User

public class User {

    @Id
    private Long id;

    private String username;
    private Integer age;


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public User() {
    }

    public User(Long id, String username, Integer age) {
        this.id = id;
        this.username = username;
        this.age = age;
    }
}

實現(xiàn)用戶實體User的數(shù)據(jù)訪問對象

public interface UserRepository extends MongoRepository<User, Long> {

    User findByUsername(String username);

}

接下來創(chuàng)建一個單元測試用例:

@SpringBootTest(classes = Application.class)
public class ApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws Exception {
        userRepository.deleteAll();

        // 創(chuàng)建三個User,并驗證User總數(shù)
        userRepository.save(new User(1L, "麻衣**", 22));
        userRepository.save(new User(2L, "娜*", 24));
        userRepository.save(new User(3L, "玩偶**", 26));
        Assertions.assertEquals(3, userRepository.findAll().size());

        // 刪除一個User,再驗證User總數(shù)
        User u = userRepository.findById(1L).get();
        userRepository.delete(u);
        Assertions.assertEquals(2, userRepository.findAll().size());

        // 刪除一個User,再驗證User總數(shù)
        u = userRepository.findByUsername("娜*");
        userRepository.delete(u);
        Assertions.assertEquals(1, userRepository.findAll().size());
    }

}

控制臺輸出

2023-11-17 15:39:39.655  INFO 15808 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2023-11-17 15:39:39.737  INFO 15808 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:26}] to localhost:27017
2023-11-17 15:39:39.737  INFO 15808 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:27}] to localhost:27017
2023-11-17 15:39:39.737  INFO 15808 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=17, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=58204100}
2023-11-17 15:39:39.963  INFO 15808 --- [           main] c.miaow.demo.ApplicationTests   : Started ApplicationTests in 2.079 seconds (JVM running for 2.619)
2023-11-17 15:39:40.106  INFO 15808 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:28}] to localhost:27017
2023-11-17 15:39:40.184  INFO 15808 --- [extShutdownHook] org.mongodb.driver.connection            : Closed connection [connectionId{localValue:3, serverValue:28}] to localhost:27017 because the pool has been closed.
2023-11-17 15:39:40.184  INFO 15808 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

注意,MongoDB的語法有所區(qū)別,具體的如下:

查詢語法:

插入文檔:db.collection.insertOne(document)db.collection.insertMany(documents)

查詢文檔:db.collection.find(query, projection)

更新文檔:db.collection.updateOne(filter, update)db.collection.updateMany(filter, update)

刪除文檔:db.collection.deleteOne(filter)db.collection.deleteMany(filter)

條件查詢:db.collection.find({ field: value })

范圍查詢:db.collection.find({ field: { $gt: value1, $lt: value2 } })
正則表達式查詢:db.collection.find({ field: /pattern/ })

排序:db.collection.find().sort({ field: 1 })(1表示升序,-1表示降序)

分頁:db.collection.find().skip(offset).limit(limit)

聚合查詢:db.collection.aggregate(pipeline)

在Java中的相關(guān)操作:

連接MongoDB:使用MongoClient類來連接MongoDB數(shù)據(jù)庫。

普通連接方式,如果是Spring Boot中就是配置一下

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("mydatabase");

獲取集合:使用getCollection方法獲取集合對象。

MongoCollection<Document> collection = database.getCollection("mycollection");

插入文檔:

Document document = new Document("name", "miaow")
    .append("age", 24)
    .append("email", "miaow@example.com");
collection.insertOne(document);

查詢文檔:

FindIterable<Document> result = collection.find(new Document("name", "miaow"));
for (Document document : result) {
    // 處理查詢結(jié)果
}

更新文檔:

collection.updateOne(eq("name", "miaow"), new Document("$set", new Document("age", 24)));

刪除文檔:

collection.deleteOne(eq("name", "miaow"));

以上就是在SpringBoot中使用MongoDB完成數(shù)據(jù)存儲的詳細內(nèi)容,更多關(guān)于SpringBoot MongoDB數(shù)據(jù)存儲的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Spring Boot 發(fā)送郵件功能案例分析

    Spring Boot 發(fā)送郵件功能案例分析

    這篇文章主要介紹了 Spring Boot 發(fā)送郵件功能,本文通過代碼結(jié)合案例分析給大家介紹的非常詳細,需要的朋友可以參考下
    2017-11-11
  • Log4j如何屏蔽某個類的日志打印

    Log4j如何屏蔽某個類的日志打印

    這篇文章主要介紹了Log4j如何屏蔽某個類的日志打印,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • OpenFeign如何解決Get請求自動轉(zhuǎn)化成POST的問題

    OpenFeign如何解決Get請求自動轉(zhuǎn)化成POST的問題

    這篇文章主要介紹了OpenFeign如何解決Get請求自動轉(zhuǎn)化成POST的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • 一文詳解MVCC的執(zhí)行原理

    一文詳解MVCC的執(zhí)行原理

    MVCC是一種并發(fā)控制機制,用于解決數(shù)據(jù)庫并發(fā)訪問中,數(shù)據(jù)一致性問題,它通過在讀寫操作期間保存多個數(shù)據(jù)版本,以提供并發(fā)事務(wù)間的隔離性,本文將和大家簡單聊聊MVCC的執(zhí)行原理,需要的朋友可以參考下
    2023-12-12
  • Mybatis 簡介與原理

    Mybatis 簡介與原理

    MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的持久層框架。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集
    2017-05-05
  • 解決Mybatis-Plus操作分頁后數(shù)據(jù)失效問題

    解決Mybatis-Plus操作分頁后數(shù)據(jù)失效問題

    這篇文章主要介紹了解決Mybatis-Plus操作分頁后數(shù)據(jù)失效問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • 帶你3分鐘帶你搞定Spring Boot中Schedule

    帶你3分鐘帶你搞定Spring Boot中Schedule

    本文主要圍繞Spring scheduled應(yīng)用實踐進行分享,如果是單體應(yīng)用,使用SpringBoot內(nèi)置的@scheduled注解可以解決大部分業(yè)務(wù)需求,對Spring Boot中Schedule 相關(guān)知識感興趣的朋友一起看看吧
    2024-07-07
  • Spring Boot自定義Banner實現(xiàn)代碼

    Spring Boot自定義Banner實現(xiàn)代碼

    這篇文章主要介紹了Spring Boot自定義Banner實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • @Value如何獲取yml和properties配置參數(shù)

    @Value如何獲取yml和properties配置參數(shù)

    這篇文章主要介紹了@Value如何獲取yml和properties配置參數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java使用延時隊列搞定超時訂單處理的場景

    Java使用延時隊列搞定超時訂單處理的場景

    這篇文章主要介紹了Java使用延時隊列搞定超時訂單處理,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-08-08

最新評論