Eclipse JNoSQLガイド

Eclipse JNoSQLガイド

1. 概要

EclipseJNoSQLは、simplify the interaction of Java applications with NoSQL databasesであるAPIと実装のセットです。

この記事では、NoSQLデータベースと対話するようにJNoSQLを設定および構成する方法を学習します。 コミュニケーションレイヤーとマッピングレイヤーの両方を使用します。

2. EclipseJNoSQL通信レイヤー

技術的に言えば、通信層は2つのモジュールで構成されています:Diana API and a driver.

While the API defines an abstraction to NoSQL database types, the driver provides implementations for most known databases

これを、リレーショナルデータベースのJDBC APIおよびJDBCドライバーと比較できます。

2.1. Eclipse JNoSQL Diana API

簡単に言えば、NoSQLデータベースには、Key-Value、Column、Document、Graphの4つの基本タイプがあります。

また、Eclipse JNoSQL Diana APIは3つのモジュールを定義しています。

  1. ダイアナキー値

  2. ダイアナ列

  3. ダイアナ文書

NoSQLグラフタイプは、すでにApache ThinkerPopでカバーされているため、APIではカバーされていません。

APIは、コアモジュールdiana-coreに基づいており、Configuration、Factory、Manager、Entity、Valueなどの一般的な概念の抽象化を定義します。

APIを使用するには、対応するモジュールの依存関係をNoSQLデータベースタイプに提供する必要があります。

したがって、ドキュメント指向データベースの場合、diana-documentの依存関係が必要になります。


    org.jnosql.diana
    diana-document
    0.0.5

同様に、動作中のNoSQLデータベースがKey-Value指向の場合は、diana-key-valueモジュールを使用する必要があります。


    org.jnosql.diana
    diana-key-value
    0.0.5

最後に、列指向の場合はdiana-columnモジュール:


    org.jnosql.diana
    diana-column
    0.0.5

最新バージョンはMaven Centralにあります。

2.2. Eclipse JNoSQL Dianaドライバー

The driver is a set of implementations of the API for the most common NoSQL databases

NoSQLデータベースごとに1つの実装があります。 If the database is multi-model, the driver should implement all supported APIs

たとえば、Couchbaseはドキュメントとキー値の両方を対象としているため、couchbase-driverdiana-documentdiana-key-valueの両方を実装します。

ドライバーが通常データベースベンダーによって提供されるリレーショナルデータベースとは異なり、ここではthe driver is provided by Eclipse JNoSQLです。 ほとんどの場合、このドライバーは公式ベンダーライブラリのラッパーです。

ドライバーの使用を開始するには、選択したNoSQLデータベースのAPIと対応する実装を含める必要があります。

たとえば、MongoDBの場合、次の依存関係を含める必要があります。


    org.jnosql.diana
    diana-document
    0.0.5


    org.jnosql.diana
    mongodb-driver
    0.0.5

ドライバーでの作業の背後にあるプロセスは簡単です。

まず、Configurationbeanが必要です。 クラスパスまたはハードコーディング値から構成ファイルを読み取ることにより、ConfigurationFactory.を作成できます。次に、それを使用してManager.を作成します。

Finally, The Manager is responsible for pushing and retrieving the Entity to and from the NoSQL database

次のサブセクションでは、NoSQLデータベースタイプごとにこのプロセスについて説明します。

2.3. ドキュメント指向データベースの操作

この例では、we’ll be using an embedded MongoDBは使い始めるのが簡単で、インストールを必要としないためです。 これはドキュメント指向であり、次の手順は他のドキュメント指向のNoSQLデータベースに適用できます。

最初に、アプリケーションがデータベースと適切に対話するために必要なすべての設定を提供する必要があります.最も基本的な形式では、hostportを提供する必要があります。 MongoDBの実行中のインスタンス。

これらの設定は、クラスパスにあるmongodb-driver.propertiesのいずれかで提供できます。

#Define Host and Port
mongodb-server-host-1=localhost:27017

または、ハードコーディングされた値として:

Map map = new HashMap<>();
map.put("mongodb-server-host-1", "localhost:27017");

次に、ドキュメントタイプのConfigurationBeanを作成します。

DocumentConfiguration configuration = new MongoDBDocumentConfiguration();

このConfiguration Beanから、ManagerFactoryを作成できます。

DocumentCollectionManagerFactory managerFactory = configuration.get();

暗黙的に、Configuration Beanのget()メソッドは、プロパティファイルの設定を使用します。 ハードコードされた値からこのファクトリを取得することもできます。

DocumentCollectionManagerFactory managerFactory
  = configuration.get(Settings.of(map));

ManagerFactoryには、データベース名をパラメーターとして受け取り、Managerを作成する単純なメソッドget(),があります。

DocumentCollectionManager manager = managerFactory.get("my-db");

そして最後に、準備が整いました。 Manager は、DocumentEntity.を介して基盤となるNoSQLデータベースと対話するために必要なすべてのメソッドを提供します

したがって、たとえば、ドキュメントを挿入できます。

DocumentEntity documentEntity = DocumentEntity.of("books");
documentEntity.add(Document.of("_id", "100"));
documentEntity.add(Document.of("name", "JNoSQL in Action"));
documentEntity.add(Document.of("pages", "620"));
DocumentEntity saved = manager.insert(documentEntity);

ドキュメントを検索することもできます。

DocumentQuery query = select().from("books").where("_id").eq(100).build();
List entities = manager.select(query);

同様の方法で、既存のドキュメントを更新できます。

saved.add(Document.of("author", "example"));
DocumentEntity updated = manager.update(saved);

最後に、保存されたドキュメントを削除できます。

DocumentDeleteQuery deleteQuery = delete().from("books").where("_id").eq("100").build();
manager.delete(deleteQuery);

サンプルを実行するには、jnosql-dianaモジュールにアクセスして、DocumentAppアプリケーションを実行する必要があります。

コンソールに出力が表示されるはずです。

DefaultDocumentEntity{documents={pages=620, name=JNoSQL in Action, _id=100}, name='books'}
DefaultDocumentEntity{documents={pages=620, author=example, name=JNoSQL in Action, _id=100}, name='books'}
[]

2.4. 列指向データベースの操作

このセクションでは、we’ll use an embedded version of the Cassandra databaseであるため、インストールは必要ありません。

列指向データベースを操作するプロセスは非常に似ています。 まず、Cassandraドライバーと列APIをpomに追加します。


    org.jnosql.diana
    diana-column
    0.0.5


    org.jnosql.diana
    cassandra-driver
    0.0.5

次に、構成ファイルで指定された構成設定が必要です。クラスパスのdiana-cassandra.properties, です。 または、ハードコードされた構成値を使用することもできます。

次に、同様のアプローチで、ColumnFamilyManagerを作成し、ColumnEntity:の操作を開始します。

ColumnConfiguration configuration = new CassandraConfiguration();
ColumnFamilyManagerFactory managerFactory = configuration.get();
ColumnFamilyManager entityManager = managerFactory.get("my-keySpace");

したがって、新しいエンティティを作成するには、insert()メソッドを呼び出します。

ColumnEntity columnEntity = ColumnEntity.of("books");
Column key = Columns.of("id", 10L);
Column name = Columns.of("name", "JNoSQL in Action");
columnEntity.add(key);
columnEntity.add(name);
ColumnEntity saved = entityManager.insert(columnEntity);

サンプルを実行してコンソールに出力を表示するには、ColumnFamilyAppアプリケーションを実行します。

2.5. Key-Value指向データベースの操作

このセクションでは、Hazelcastを使用します。 Hazelcast is a key-value oriented NoSQL database。 Hazelcastデータベースの詳細については、このlinkを確認できます。

キー値指向型を使用するプロセスも同様です。 これらの依存関係をpomに追加することから始めます。


    org.jnosql.diana
    diana-key-value
    0.0.5


    org.jnosql.diana
    hazelcast-driver
    0.0.5

次に、構成設定を指定する必要があります。 次に、BucketManagerを取得して、KeyValueEntity:を操作できます。

KeyValueConfiguration configuration = new HazelcastKeyValueConfiguration();
BucketManagerFactory managerFactory = configuration.get();
BucketManager entityManager = managerFactory.getBucketManager("books");

次のBookモデルを保存するとします。

public class Book implements Serializable {

    private String isbn;
    private String name;
    private String author;
    private int pages;

    // standard constructor
    // standard getters and setters
}

したがって、Bookインスタンスを作成し、put()メソッドを呼び出して保存します。

Book book = new Book(
  "12345", "JNoSQL in Action",
  "example", 420);
KeyValueEntity keyValueEntity = KeyValueEntity.of(
  book.getIsbn(), book);
entityManager.put(keyValueEntity);

次に、保存されたBookインスタンスを取得するには:

Optional optionalValue = manager.get("12345");
Value value = optionalValue.get(); // or any other adequate Optional handling
Book savedBook = value.get(Book.class);

サンプルを実行してコンソールに出力を表示するには、KeyValueAppアプリケーションを実行します。

3. EclipseJNoSQLマッピングレイヤー

The mapping layer, Artemis API, is a set of APIs that help map java annotated Objects to NoSQL databases。 これは、Diana APIとCDI(Context and Dependency Injection)に基づいています。

We can consider this API as JPA or ORM like for the NoSQL world。 このレイヤーは、各NoSQLタイプ用のAPIと、共通機能用の1つのコアAPIも提供します。

このセクションでは、MongoDBドキュメント指向データベースを使用します。

3.1. 必要な依存関係

アプリケーションでArtemisを有効にするには、artemis-configurationの依存関係を追加する必要があります。 MongoDBはドキュメント指向であるため、依存関係artemis-documentも必要です。

他のタイプのNoSQLデータベースの場合、artemis-column, artemis-key-valueartemis-graphを使用します。

MongoDB用のDianaドライバーも必要です。


    org.jnosql.artemis
    artemis-configuration
    0.0.5


    org.jnosql.artemis
    artemis-document
    0.0.5


    org.jnosql.diana
    mongodb-driver
    0.0.5

ArtemisはCDIに基づいているため、このMaven依存関係も提供する必要があります。


    javax
    javaee-web-api
    8.0
    provided

3.2. ドキュメント構成ファイル

構成とは、特定のデータベースの一連のプロパティであり、コード外の設定を提供します。 デフォルトでは、META-INFリソースの下にjnosql.jsonファイルを指定する必要があります。

これは設定ファイルの例です:

[
    {
        "description": "The mongodb document configuration",
        "name": "document",
        "provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration",
        "settings": {
            "mongodb-server-host-1":"localhost:27019"
        }
    }
]

ConfigurationUnit.name属性を設定して、上記の構成名を指定する必要があります。構成が別のファイルにある場合は、fileName属性を使用して指定できます。

この構成を前提として、ファクトリを作成します。

@Inject
@ConfigurationUnit(name = "document")
private DocumentCollectionManagerFactory managerFactory;

そして、このファクトリから、DocumentCollectionManagerを作成できます。

@Produces
public MongoDBDocumentCollectionManager getEntityManager() {
    return managerFactory.get("todos");
}

DocumentCollectionManagerはCDI対応のBeanであり、TemplateRepository.の両方で使用されます。

3.3. マッピング

マッピングは、EntityモデルがDianaEntityValue.に変換される注釈駆動型プロセスです。

Todoモデルを定義することから始めましょう:

@Entity
public class Todo implements Serializable {

    @Id("id")
    public long id;

    @Column
    public String name;

    @Column
    public String description;

    // standard constructor
    // standard getters and setters
}

上に示したように、基本的なマッピングアノテーションがあります:@Entity, @Id,@Column.

このモデルを操作するには、TemplateクラスまたはRepositoryインターフェースのいずれかが必要です。

3.4. テンプレートの操作

The template is thebridge between the entity model and the Diana API。 ドキュメント指向データベースの場合、DocumentTemplateBeanを挿入することから始めます。

@Inject
DocumentTemplate documentTemplate;

そして、Todoエンティティを操作できます。 たとえば、Todoを作成できます。

public Todo add(Todo todo) {
    return documentTemplate.insert(todo);
}

または、Todoidで取得できます。

public Todo get(String id) {
    Optional todo = documentTemplate
      .find(Todo.class, id);
    return todo.get(); // or any other proper Optional handling
}

すべてのエンティティを選択するには、DocumentQueryを作成してから、select()メソッドを呼び出します。

public List getAll() {
    DocumentQuery query = select().from("Todo").build();
    return documentTemplate.select(query);
}

そして最後に、Todoエンティティをidで削除できます。

public void delete(String id) {
    documentTemplate.delete(Todo.class, id);
}

3.5. リポジトリの操作

Templateクラスに加えて、the Repository interface which has methods for creating, updating, deleting and retrieving情報を介してエンティティを管理することもできます。

Repositoryインターフェースを使用するには、Repository:のサブインターフェースを提供するだけです。

public interface TodoRepository extends Repository {
    List findByName(String name);
    List findAll();
}

次のメソッドおよびパラメーターの命名規則により、このインターフェースの実装は実行時にCDI Beanとして提供されます。

この例では、nameが一致するすべてのTodoエンティティがfindByName()メソッドによって取得されます。

これで使用できます。

@Inject
TodoRepository todoRepository;

Database修飾子を使用すると、同じアプリケーションで複数のNoSQLデータベースを操作できます。 タイプとプロバイダーという2つの属性があります。

データベースがマルチモデルの場合、使用するモデルを指定する必要があります。

@Inject
@Database(value = DatabaseType.DOCUMENT)
TodoRepository todoRepository;

さらに、同じモデルのデータベースが複数ある場合は、プロバイダーを指定する必要があります。

@Inject
@Database(value = DatabaseType.DOCUMENT, provider="org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration")
TodoRepository todoRepository;

サンプルを実行するには、jnosql-artemisモジュールにアクセスし、次のコマンドを呼び出します。

mvn package liberty:run

このコマンドは、liberty-maven-pluginのおかげで、Open Libertyサーバーを構築、デプロイ、起動します。

3.6. アプリケーションのテスト

アプリケーションがRESTエンドポイントを公開するため、テストに任意のRESTクライアントを使用できます。 ここでは、カールツールを使用しました。

Todoクラスを保存するには:

curl -d '{"id":"120", "name":"task120", "description":"Description 120"}' -H "Content-Type: application/json" -X POST http://localhost:9080/jnosql-artemis/todos

すべてのTodoを取得するには:

curl -H "Accept: application/json" -X GET http://localhost:9080/jnosql-artemis/todos

または、Todoを1つだけ取得するには:

curl -H "Accept: application/json" -X GET http://localhost:9080/jnosql-artemis/todos/120

4. 結論

このチュートリアルでは、JNoSQLがNoSQLデータベースとの相互作用を抽象化する方法を検討しました。

First, we have used JNoSQL Diana API to interact with the database with low-level code. Then, we used the JNoSQL Artemis API to work with friendly Java annotated Models

いつものように、この記事over on Githubで使用されているコードを見つけることができます。