使用 MongoDB 和 Quarkus 入門指南

NoSQL,REST
Remote
0
03:20 AM · Dec 01 ,2025

1. 簡介

Quarkus 是一個流行的 Java 框架,針對創建具有最小內存佔用和快速啓動時間的應用程序進行了優化。

與 MongoDB(一個流行的 NoSQL 數據庫)結合使用時,Quarkus 提供了一個強大的工具包,用於開發高性能、可擴展的應用程序。

在本教程中,我們將探索使用 Quarkus 配置 MongoDB、實施基本 CRUD 操作以及使用 Panache(Quarkus 的對象文檔映射器)簡化這些操作。

2. 配置

2.1. Maven 依賴

要使用 MongoDB 與 Quarkus,我們需要包含 quarkus-mongodb-client


<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-mongodb-client</artifactId>
    <version>3.13.0</version>
</dependency>

此依賴項提供用於使用 MongoDB Java 客户端與 MongoDB 數據庫交互所需的工具。

2.2. 運行 MongoDB 數據庫

對於本文,我們將 MongoDB 運行在 Docker 容器中。 這是一個方便的方法,無需在我們的機器上直接安裝 MongoDB 即可設置 MongoDB 實例。

首先,我們將從 Docker Hub 拉取 MongoDB 鏡像:

docker pull mongo:latest

然後啓動一個新的容器:

docker run --name mongodb -d -p 27017:27017 mongo:latest

2.3. 配置 MongoDB 數據庫

主要的配置屬性是訪問 MongoDB 的 URL。 我們可以將幾乎所有的配置包含在 連接字符串 中。

我們可以配置 MongoDB 客户端用於多節點副本集,但在我們的示例中,我們將使用本地主機上的單個實例:

quarkus.mongodb.connection-string = mongodb://localhost:27017

3. Basic CRUD Operations

Now that we have our database and project ready and connected, let’s implement basic CRUD (Create, Read, Update, Delete) operations using the default Mongo client provided by Quarkus.

3.1. Defining the Entity

In this section, we will define the Article entity, representing a document in our MongoDB collection:

public class Article {
    @BsonId
    public ObjectId id;
    public String author;
    public String title;
    public String description;
    
    // getters and setters 
}

Our class includes fields for id, author, title, and description. ObjectId is a BSON (binary representation of JSON) type used as the default identifier for MongoDB documents. The @BsonId annotation designates a field as a MongoDB document’s identifier (_id).

When applied to a field, it indicates that this field should be mapped to the _id field in the MongoDB collection. Using this combination, we ensure that each Article document has a unique identifier that MongoDB can use to index and retrieve documents efficiently.

3.2. Defining the Repository

In this section, we’ll create the ArticleRepository class, using MongoClient to perform CRUD operations on the Article entity. This class will manage the connection to the MongoDB database and provide methods to create, read, update, and delete Article documents.

First, we’ll use dependency injection to get an instance of MongoClient:

@Inject
MongoClient mongoClient;

This allows us to interact with the MongoDB database without manually managing the connection.

We define a helper method getCollection() to get the articles collection from the articles database:

private MongoCollection<Article> getCollection() {
    return mongoClient.getDatabase("articles").getCollection("articles", Article.class);
}

Now, we can use the collection provider to perform basic CRUD operations:

public void create(Article article) {
    getCollection().insertOne(article);
}

The create() method inserts a new Article document into the MongoDB collection. This method uses insertOne() to add the provided article object, ensuring it is stored as a new entry in the articles collection.

public List<Article> listAll() {
    return getCollection().find().into(new ArrayList<>());
}

The listAll() method retrieves all Article documents from the MongoDB collection. It leverages the find() method to query all documents and collect them. We can also specify the type of collection that we want to return.

public void update(Article article) {
    getCollection().replaceOne(new org.bson.Document("_id", article.id), article);
}

The update() method replaces an existing Article document with the provided object. It uses replaceOne() to find the document with the matching _id and updates it with the new data.

public void delete(String id) {
    getCollection().deleteOne(new org.bson.Document("_id", new ObjectId(id)));
}

The delete() method removes an Article document from the collection by its id. It constructs a filter to match the _id and uses deleteOne to remove the first document that matches this filter.

3.3. Defining the Resource

As a brief example, we’ll limit ourselves to defining the resource and the repository without currently implementing the service layer.

Now, all we need to do is create our resource, inject the repository, and create a method for every operation:

@Path("/articles")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ArticleResource {
    @Inject
    ArticleRepository articleRepository;

    @POST
    public Response create(Article article) {
        articleRepository.create(article);
        return Response.status(Response.Status.CREATED).build();
    }

    @GET
    public List<Article> listAll() {
        return articleRepository.listAll();
    }

    @PUT
    public Response update(Article updatedArticle) {
        articleRepository.update(updatedArticle);
        return Response.noContent().build();
    }

    @DELETE
    @Path("/{id}")
    public Response delete(@PathParam("id") String id) {
        articleRepository.delete(id);
        return Response.noContent().build();
    }
}

3.4. Testing Our API

To ensure our API is working correctly, we can use curl, a versatile command-line tool for transferring data using various network protocols.

We’ll add a new article to the database. We use the HTTP POST method to send a JSON payload representing the article to the/articles endpoint:

curl -X POST http://localhost:8080/articles \
-H "Content-Type: application/json" \
-d '{"author":"John Doe","title":"Introduction to Quarkus","description":"A comprehensive guide to Quarkus framework."}'

To verify that our article was successfully stored, we can use the HTTP GET method to fetch all articles from the database:

curl -X GET http://localhost:8080/articles

By running this we’ll get a JSON array containing all the articles currently stored in the database:

[
  {
    "id": "66a8c65e8bd3a01e0a509f0a",
    "author": "John Doe",
    "title": "Introduction to Quarkus",
    "description": "A comprehensive guide to Quarkus framework."
  }
]

4. 使用 Panache 與 MongoDB

Quarkus 提供了一個額外的抽象層,稱為 Panache,它簡化了數據庫操作並減少了樣板代碼。 使用 Panache,我們可以更專注於業務邏輯,而不是數據訪問代碼。 讓我們看看如何使用 Panache 實現相同的 CRUD 操作。

4.1. Maven 依賴

為了使用 Panache 與 MongoDB,我們需要添加 quarkus-mongodb-panache 依賴項:


<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-mongodb-panache</artifactId>
    <version>3.13.0</version>
</dependency>

4.2. 定義實體

當使用 Panache 時,我們的實體類將擴展 PanacheMongoEntity,該類提供用於常見數據庫操作的內置方法。 此外,我們還將使用 @MongoEntity 註解來定義我們的 MongoDB 集合:


@MongoEntity(collection = "articles", database = "articles")
public class Article extends PanacheMongoEntityBase {
    private ObjectId id;
    private String author;
    private String title;
    private String description;

    // getters and setters
}

4.3. 定義存儲庫

使用 Panache,我們通過擴展 PanacheMongoRepository 創建存儲庫。 這使我們能夠使用 CRUD 操作和管理 MongoDB 實體,而無需編寫樣板代碼:


@ApplicationScoped
public class ArticleRepository implements PanacheMongoRepository<Article> {}

當擴展 PanacheMongoRepository 類時,許多常用的方法變得可用,用於執行 CRUD 操作和管理 MongoDB 實體。 現在,我們可以使用諸如 persist(), listAll(), findById 等方法直接使用。

4.4. 定義資源

現在,我們只需要創建我們的新資源,該資源將使用新的存儲庫,而無需編寫所有樣板代碼:


@Path("/v2/articles")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ArticleResource 
    @Inject
    ArticleRepository articleRepository;

    @POST
    public Response create(Article article) {
        articleRepository.persist(article);
        return Response.status(Response.Status.CREATED).build();
    }

    @GET
    public List<Article> listAll() {
        return articleRepository.listAll();
    }

    @PUT
    public Response update(Article updatedArticle) {
        articleRepository.update(updatedArticle);
        return Response.noContent().build();
    }

    @DELETE
    @Path("/{id}")
    public Response delete(@PathParam("id") String id) {
        articleRepository.delete(id);
        return Response.noContent().build();
    }
}

4.5. 測試 API

我們還可以測試新的 API,使用其他示例中相同的 curl 命令。 唯一的變化是調用的端點,這次調用 /v2/articles API。 我們將創建一個新的文章:

curl -X POST http://localhost:8080/v2/articles \
-H "Content-Type: application/json" \
-d '{"author":"John Doe","title":"Introduction to MongoDB","description":"A comprehensive guide to MongoDB."}'

然後,我們檢索現有的文章:

curl -X GET http://localhost:8080/v2/articles

5. 結論

在本文中,我們探討了如何將 MongoDB 集成到 Quarkus 中。我們配置了 MongoDB 並在 Docker 容器中運行它,為我們的應用程序設置了一個健壯且可擴展的環境。我們演示了使用默認的 Mongo 客户端執行 CRUD 操作的實現。

此外,我們介紹了 Panache,Quarkus 的對象文檔映射器 (ODM),它通過減少樣板代碼,顯著簡化了數據訪問。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.