しばらくの間、何らかの形のリレーショナルデータベース管理システムを使用している場合は、おそらくMongoDBの名前に出くわしたことでしょう。 2009年に最初に導入されたmongoDbは、業界で最も人気のあるリレーショナルデータベース管理システムの1つです。 MySqlのような古いリレーショナルデータベースソフトウェアマネージャーが市場に存在しているにもかかわらず、その非常に人気の背後にある主な理由は、それがテーブルにもたらす幅広い数と優れた汎用性です。 MongoDBを使用すると、多くのニーズがなくなります。その1つは、データベースを作成し、新しいプロジェクトが開始されるたびにデータ型を定義する必要があることです。 MongoDBクライアント記事の議題:
- MongoDBクライアントの前提条件
- Mavenでプロジェクトを作成する
- 最初のJSONRESTサービスを追加する
- MongoDBデータベースの構成
- 構成されたMongoDBデータベースの実行
- フロントエンドの作成
- BSONコーデックを使用したMongoDBクライアントの簡素化
- 最終コード
ただし、MongoDBから最大限の機能を実現するには、MongoDBクライアントに精通している必要があります。この記事では、それについて説明します。
MongoDBクライアントの前提条件
この記事を完全に読むには、最初に次の前提条件を満たしている必要があります。
システムにIDEがすでに存在している。
Java Development KitまたはJDKバージョン1.8以降が、JAVA_HOMEが正しく構成された状態でインストールされている。
DockerまたはMongoDBがインストールされています。
ApacheMavenバージョン3.5.3以降。
このガイドで作成して使用したアーキテクチャは、最も単純なものの1つです。実行すると、ユーザーはリストにデータと要素を簡単に追加でき、その後、データベースで自動的に更新されます。
これに加えて、データとサーバー間のすべての通信がJSONで行われ、すべてのデータがMongoDBに保存されていることを確認しました。
はじめに
このプロジェクトを開始するには、以下の手順に従ってください。
ステップ1:Mavenでプロジェクトを作成する
最初のステップは常に新しいプロジェクトを作成することです。これを行うには、次のコードを使用します。
mvn io.quarkus:quarkus-maven-plugin:0.22.0:create -DprojectGroupId=org.acme -DprojectArtifactId=using-mongodb-client -DclassName="org.acme.rest.json.FruitResource" -Dpath="/fruits" -Dextensions="resteasy-jsonb,mongodb-client"
上記のコマンドを実行すると、IDEはJSON-B、MongoDb、およびRESTEasy/JAX-RSクライアントをシステムにインポートします。
ステップ2に進みます。
ステップ2:最初のJSONRESTサービスを追加する
In order to do this, use the code below.
package org.acme.rest.json;
import java.util.Objects;
public class Fruit {
private String name;
private String description;
public Fruit() {
}
public Fruit(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Fruit)) {
return false;
}
Fruit other = (Fruit) obj;
return Objects.equals(other.name, this.name);
}
@Override
public int hashCode() {
return Objects.hash(this.name);
}
}
上記の例では、最初にフルーツを作成しました。これは後でプログラムで使用されます。
次に、アプリケーションのユーザーレイヤーとなるorg.acme.rest.json.FruitServiceファイルを作成する必要があります。これを行うには、以下のコードを使用してください。
package org.acme.rest.json;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
@ApplicationScoped
public class FruitService {
@Inject MongoClient mongoClient;
public List list(){
List list = new ArrayList<>();
MongoCursor cursor = getCollection().find().iterator();
try {
while (cursor.hasNext()) {
Document document = cursor.next();
Fruit fruit = new Fruit();
fruit.setName(document.getString("name"));
fruit.setDescription(document.getString("description"));
list.add(fruit);
}
} finally {
cursor.close();
}
return list;
}
public void add(Fruit fruit){
Document document = new Document()
.append("name", fruit.getName())
.append("description", fruit.getDescription());
getCollection().insertOne(document);
}
private MongoCollection getCollection(){
return mongoClient.getDatabase("fruit").getCollection("fruit");
}
}
Now we need to edit the org.acme.rest.json.FruitResource class to suit our needs. In order to do this, use the code below.
@Path("/fruits")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class FruitResource {
@Inject FruitService fruitService;
@GET
public List list() {
return fruitService.list();
}
@POST
public List add(Fruit fruit) {
fruitService.add(fruit);
return list();
}
}
ステップ3に進みます。
ステップ#3:mongoDbデータベースの構成
mongoDbデータベースを構成するための構文と標準コードは次のとおりです。
# configure the mongoDB client for a replica set of two nodes quarkus.mongodb.connection-string = mongodb://mongo1:27017,mongo2:27017
この例では、次のコードを使用してデータベースを構成します。
# configure the mongoDB client for a replica set of two nodes quarkus.mongodb.connection-string = mongodb://localhost:27017
ステップ4に進みます。
ステップ4:構成済みのMongoDBデータベースを実行する
次のステップは、作成したばかりのMongoDBデータベースを実行することです。これを行うには、以下のコードを使用してください。
docker run -ti --rm -p 27017:27017 mongo:4.0
ステップ5に進みます。
ステップ5:フロントエンドの作成
アプリケーションのバックエンドでのすべての作業が完了したので、アプリケーションのフロントエンドのコーディングに使用されるコードを見てみましょう。
package org.acme.rest.json;
import io.quarkus.mongodb.ReactiveMongoClient;
import io.quarkus.mongodb.ReactiveMongoCollection;
import org.bson.Document;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;
import java.util.concurrent.CompletionStage;
@ApplicationScoped
public class ReactiveFruitService {
@Inject
ReactiveMongoClient mongoClient;
public CompletionStage<List> list(){
return getCollection().find().map(doc -> {
Fruit fruit = new Fruit();
fruit.setName(doc.getString("name"));
fruit.setDescription(doc.getString("description"));
return fruit;
}).toList().run();
}
public CompletionStage add(Fruit fruit){
Document document = new Document()
.append("name", fruit.getName())
.append("description", fruit.getDescription());
return getCollection().insertOne(document);
}
private ReactiveMongoCollection getCollection(){
return mongoClient.getDatabase("fruit").getCollection("fruit");
}
}
package org.acme.rest.json;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.concurrent.CompletionStage;
@Path("/reactive_fruits")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ReactiveFruitResource {
@Inject ReactiveFruitService fruitService;
@GET
public CompletionStage<List> list() {
return fruitService.list();
}
@POST
public CompletionStage<List> add(Fruit fruit) {
fruitService.add(fruit);
return list();
}
}
上記の例では、リアクティブなmongoDbクライアントを使用して、フロントエンドの形成を容易にしています。
手順6に進みます。
ステップ#6:BSONコーデックを使用してmongoDbクライアントを簡素化する
これを行うには、以下のコードを使用してください。
package org.acme.rest.json.codec;
import com.mongodb.MongoClient;
import org.acme.rest.json.Fruit;
import org.bson.*;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectibleCodec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import java.util.UUID;
public class FruitCodec implements CollectibleCodec {
private final Codec documentCodec;
public FruitCodec() {
this.documentCodec = MongoClient.getDefaultCodecRegistry().get(Document.class);
}
@Override
public void encode(BsonWriter writer, Fruit fruit, EncoderContext encoderContext) {
Document doc = new Document();
doc.put("name", fruit.getName());
doc.put("description", fruit.getDescription());
documentCodec.encode(writer, doc, encoderContext);
}
@Override
public Class getEncoderClass() {
return Fruit.class;
}
@Override
public Fruit generateIdIfAbsentFromDocument(Fruit document) {
if (!documentHasId(document)) {
document.setId(UUID.randomUUID().toString());
}
return document;
}
@Override
public boolean documentHasId(Fruit document) {
return document.getId() != null;
}
@Override
public BsonValue getDocumentId(Fruit document) {
return new BsonString(document.getId());
}
@Override
public Fruit decode(BsonReader reader, DecoderContext decoderContext) {
Document document = documentCodec.decode(reader, decoderContext);
Fruit fruit = new Fruit();
if (document.getString("id") != null) {
fruit.setId(document.getString("id"));
}
fruit.setName(document.getString("name"));
fruit.setDescription(document.getString("description"));
return fruit;
}
}
次に、CodecProviderを使用して、これを既存のFruitクラスにリンクします。
package org.acme.rest.json.codec;
import org.acme.rest.json.Fruit;
import org.bson.codecs.Codec;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
public class FruitCodecProvider implements CodecProvider {
@Override
public Codec get(Class clazz, CodecRegistry registry) {
if (clazz == Fruit.class) {
return (Codec) new FruitCodec();
}
return null;
}
}
手順7に進みます。
ステップ#7:最終コード
このアプリケーションの最終的なコードは、次のようになります。
package org.acme.rest.json;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
@ApplicationScoped
public class CodecFruitService {
@Inject MongoClient mongoClient;
public List list(){
List list = new ArrayList<>();
MongoCursor cursor = getCollection().find().iterator();
try {
while (cursor.hasNext()) {
list.add(cursor.next());
}
} finally {
cursor.close();
}
return list;
}
public void add(Fruit fruit){
getCollection().insertOne(fruit);
}
private MongoCollection getCollection(){
return mongoClient.getDatabase("fruit").getCollection("fruit", Fruit.class);
}
}
結論
これで、システムでMongoDBクライアントを構成して使用する方法がわかりました。先に進んで、システムでこれらのコードを試して、経験を知らせてください。
記事の概要
MongoDBクライアントのすべてと、さまざまな用途のためにシステムで同じものを構成する方法について説明します。詳細については、以下をお読みください。
これで、“ の終わりになります MongoDBクライアント」 記事。
MongoDB認定トレーニングコースの今後のバッチ| コース名 | 日付 | |
|---|---|---|
| MongoDB認定トレーニングコース | クラスは2022年6月4日に始まります 6月4日 SAT&SUN(週末バッチ) | |
| MongoDB認定トレーニングコース | クラスは2022年8月6日に始まります 8月6日 SAT&SUN(週末バッチ) |