1. Overview
1.概述
OrientDB is an open source Multi-Model NoSQL database technology designed to work with the Graph, Document, Key-Value, GeoSpatial and Reactive models while managing queries with SQL syntax.
OrientDB是一种开源的多模型NoSQL数据库技术,旨在与图形、文档、关键值、地理空间和反应式模型一起工作,同时用SQL语法管理查询。
In this article, we’ll cover the setup and use the OrientDB Java APIs.
在这篇文章中,我们将介绍OrientDB Java APIs的设置和使用。
2. Installation
2.安装
Firstly, we need to install the binary package.
首先,我们需要安装二进制包。
Let’s download the latest stable version of OrientDB (2.2.x at the point of writing this article).
让我们下载OrientDB的最新稳定版本(在撰写本文时为2.2.x)。
Secondly, we need to unzip it and move its content to a convenient directory (using ORIENTDB_HOME). Please make sure to add the bin folder to the environment variables for any easy command-line use.
其次,我们需要解压并将其内容移到一个方便的目录中(使用ORIENTDB_HOME)。请确保将bin文件夹添加到环境变量中,以方便命令行使用。
Finally, we need to edit the orientdb.sh file located in $ORIENTDB_HOME/bin by filling the location (ORIENTDB_HOME) of OrientDB directory in the place of ORIENTDB_DIR and also the system user we’d like to use instead of USER_YOU_WANT_ORIENTDB_RUN_WITH.
最后,我们需要编辑orientdb.sh 位于$ORIENTDB_HOME/bin的文件,在ORIENTDB_DIR 以及我们想使用的系统用户,而不是USER_YOU_WANT_ORIENTDB_RUN_WITH。
Now we’ve got a fully working OrientDB. We can use the orientdb.sh <option> script with options:
现在我们已经有了一个完全工作的OrientDB。我们可以使用orientdb.sh <option> 脚本与选项。
- start: to start the server
-
status: to check the status
status:检查状态。
- stop: to stop the server
Please note that both start and stop actions require the user password (the one we set up in the orientdb.sh file).
请注意,启动和停止操作都需要用户密码(我们在orientdb.sh文件中设置的密码)。。
Once the server is launched, it’ll occupy the port 2480. Therefore we can access it locally using this URL:
一旦服务器启动,它将占用2480端口。因此,我们可以使用这个URL:在本地访问它。
More details of manual installation can be found here.
关于手动安装的更多细节可以在这里找到。。
Note: OrientDB requires Java version 1.7 or higher.
注意:OrientDB需要Java版本1.7或更高。
Previous versions are available here.
以前的版本可在这里获得。
3. OrientDB Java APIs Setup
3.OrientDB的Java APIs设置
The OrientDB allows Java developers to work with three different APIs such as:
OrientDB允许Java开发人员使用三种不同的API,如:。
- Graph API – graph databases
- Document API – document-oriented databases
- Object API – objects that are bound directly to OrientDB Document
We can use all those types within a single codebase just by integrating and using OrientDB.
我们可以在一个代码库中使用所有这些类型,只需集成和使用OrientDB。
Let’s have a look at some available jars we can include in the classpath of the project:
让我们看一下我们可以在项目的classpath中包含的一些可用的jars。
- orientdb-core-*.jar: brings the core library
- blueprints-core-*.jar: to bring the adapters core components
- orientdb-graphdb-*.jar: gives the Graph database API
- orientdb-object-*.jar: furnishes the Object database API
- orientdb-distributed-*.jar: provides the distributed database plugin to work with a server cluster
- orientdb-tools-*.jar: hands over the console command
- orientdb-client-*.jar: provides the remote client
- orientdb-enterprise-*.jar: enables the protocol and network classes shared by the client and server
The two last ones are required only if we’re managing our data on a remote server.
只有当我们在远程服务器上管理我们的数据时,才需要最后两个。
Let’s start with a Maven project and use the following dependencies:
让我们从一个Maven项目开始,并使用以下依赖关系。
<dependency>
<groupId>com.orientechnologies</groupId>
<artifactId>orientdb-core</artifactId>
<version>2.2.31</version>
</dependency>
<dependency>
<groupId>com.orientechnologies</groupId>
<artifactId>orientdb-graphdb</artifactId>
<version>2.2.31</version>
</dependency>
<dependency>
<groupId>com.orientechnologies</groupId>
<artifactId>orientdb-object</artifactId>
<version>2.2.31</version>
</dependency>
<dependency>
<groupId>com.tinkerpop.blueprints</groupId>
<artifactId>blueprints-core</artifactId>
<version>2.6.0</version>
</dependency>
Please check the Maven Central repository for the latest versions of OrientDB’s Core, GraphDB, Object APIs and the Blueprints-Core.
请查看Maven Central仓库,了解OrientDB的Core、GraphDB、ObjectAPI的最新版本以及Blueprints-Core。
4. Usage
4.使用情况
The OrientDB is using the TinkerPop Blueprints implementation for working with graphs.
OrientDB使用TinkerPop Blueprints实现来处理图形。
TinkerPop is a Graph Computing Framework providing many ways of building graph databases, where each of them has its implementations:
TinkerPop是一个图计算框架,提供了许多构建图数据库的方法,其中每个方法都有其实现方式。
Moreover, OrientDB allows to work with the three kinds of Schemas regardless the type of API:
此外,OrientDB允许使用三种构架,而不管API的类型如何。
- Schema-Full – strict mode is enabled, so all the fields are specified during class creation
- Schema-Less – classes are created with no specific property, so we can add them as we want; it’s the default mode
- Schema-Hybrid – it’s the mix of schema-full and schema-less where we can create a class with pre-defined fields but let the record to define other custom ones
4.1. Graph API
4.1.图形API
Since this is a graph-based database, data is represented as a network containing Vertices (nodes) interconnected by Edges (arcs).
由于这是一个基于图形的数据库,数据被表示为一个包含顶点(节点)的网络,由边缘(弧)相互连接。
As a first step, let’s use the UI to create a Graph database called BaeldungDB with a user admin and password admin.
作为第一步,让我们使用用户界面来创建一个名为BaeldungDB的图形数据库,用户为admin,密码为admin。
As we see in the subsequent image, the graph has been selected as database type, so consequently its data will be accessible in the GRAPH Tab:
正如我们在随后的图片中看到的,图形已经被选为数据库类型,因此它的数据将在GRAPH标签中被访问。
Let’s now connect to the desired database, knowing that the ORIENTDB_HOME is an environment variable that corresponds to the installation folder of OrientDB:
现在让我们连接到所需的数据库,知道ORIENTDB_HOME是一个环境变量,对应于OrientDB的安装文件夹。
@BeforeClass
public static void setup() {
String orientDBFolder = System.getenv("ORIENTDB_HOME");
graph = new OrientGraphNoTx("plocal:" + orientDBFolder +
"/databases/BaeldungDB", "admin", "admin");
}
Let’s initiate the Article, Author, and Editor classes – while showing how to add validation to their fields:
让我们启动Article、Author和Editor类–同时展示如何为其字段添加验证。
@BeforeClass
public static void init() {
graph.createVertexType("Article");
OrientVertexType writerType
= graph.createVertexType("Writer");
writerType.setStrictMode(true);
writerType.createProperty("firstName", OType.STRING);
// ...
OrientVertexType authorType
= graph.createVertexType("Author", "Writer");
authorType.createProperty("level", OType.INTEGER).setMax("3");
OrientVertexType editorType
= graph.createVertexType("Editor", "Writer");
editorType.createProperty("level", OType.INTEGER).setMin("3");
Vertex vEditor = graph.addVertex("class:Editor");
vEditor.setProperty("firstName", "Maxim");
// ...
Vertex vAuthor = graph.addVertex("class:Author");
vAuthor.setProperty("firstName", "Jerome");
// ...
Vertex vArticle = graph.addVertex("class:Article");
vArticle.setProperty("title", "Introduction to ...");
// ...
graph.addEdge(null, vAuthor, vEditor, "has");
graph.addEdge(null, vAuthor, vArticle, "wrote");
}
In the code snippet above, we made a simple representation of our simple database where:
在上面的代码片段中,我们对我们的简单数据库做了一个简单的表示,其中。
- Article is the schema-less class that contains articles
- Writer is a schema-full super-class that holds necessary writer information
- Writer is a sub-type of Author that holds its details
- Editor is a schema-less sub-type of Writer that holds editor details
- lastName field hasn’t been filled in the saved author but still appears on the following graph
- we have a relation between all classes: an Author can write Article and needs to have an Editor
- Vertex represents an entity with some fields
- Edge is an entity that links two Vertices
Please note that by trying to add another property to an object of a full class we’ll end up with the OValidationException.
请注意,如果试图向一个完整类的对象添加另一个属性,我们最终会遇到OvalidationException。。
After connecting to our database using OrientDB studio, we’ll see the graph representation of our data:
在使用OrientDB studio连接到我们的数据库后,我们将看到数据的图形表示。
Let’s see how to have the number of all records (vertices) of the database:
让我们看看如何拥有数据库的所有记录(顶点)的数量。
long size = graph.countVertices();
Now, let’s show just the number of Writer (Author & Editor) objects:
现在,让我们只显示作家(作者& 编辑)对象的数量。
@Test
public void givenBaeldungDB_checkWeHaveTwoWriters() {
long size = graph.countVertices("Writer");
assertEquals(2, size);
}
In the next step, we can find all Writer‘s data, using the following statement:
在下一步,我们可以找到所有Writer的数据,使用以下语句。
Iterable<Vertex> writers = graph.getVerticesOfClass("Writer");
Finally, let’s query for all Editor‘s with level 7; here we only have one that matches:
最后,让我们查询所有Editor的级别7;这里我们只有一个匹配的。
@Test
public void givenBaeldungDB_getEditorWithLevelSeven() {
String onlyEditor = "";
for(Vertex v : graph.getVertices("Editor.level", 7)) {
onlyEditor = v.getProperty("firstName").toString();
}
assertEquals("Maxim", onlyEditor);
}
The class name is always specified to look for a specific vertice when requesting. We can find more details here.
在请求时,总是指定类名来寻找特定的顶点。我们可以找到更多的细节这里。
4.2. Document API
4.2.文档API
Next option is to use the OrientDB’s Document model. This exposes data manipulation via a simple record with information stored in fields where the type could be text, picture or a binary form.
下一个选择是使用OrientDB的Document模型。这通过一个简单的记录暴露了数据操作,信息存储在字段中,类型可以是文本、图片或二进制形式。
Let’s use the UI again to create a database named BaeldungDBTwo, but now with a document as type:
让我们再次使用用户界面来创建一个名为BaeldungDBTwo的数据库,但现在是以document作为类型。
Note: likewise this API also can be used either in schema-full, schema-less or schema-hybrid mode.
注意:同样地,这个API也可以在满模式、无模式或混合模式下使用。
The database connection remains straightforward as we just need to instantiate an ODatabaseDocumentTx object, provide the database URL and the database user’s credentials:
数据库连接仍然很简单,因为我们只需要实例化一个ODatabaseDocumentTx对象,提供数据库URL和数据库用户的凭证。
@BeforeClass
public static void setup() {
String orientDBFolder = System.getenv("ORIENTDB_HOME");
db = new ODatabaseDocumentTx("plocal:"
+ orientDBFolder + "/databases/BaeldungDBTwo")
.open("admin", "admin");
}
Let’s start with saving a simple document that holds an Author information.
让我们从保存一个拥有作者信息的简单文件开始。
Here we can see that the class has been automatically created:
这里我们可以看到,该类已被自动创建。
@Test
public void givenDB_whenSavingDocument_thenClassIsAutoCreated() {
ODocument doc = new ODocument("Author");
doc.field("name", "Paul");
doc.save();
assertEquals("Author", doc.getSchemaClass().getName());
}
Accordingly, to count the number of Authors, we can use:
相应地,为了计算Authors的数量,我们可以使用。
long size = db.countClass("Author");
Let’s query documents again using a field value, to search for the Author‘s objects with level 7:
让我们再次使用字段值查询文档,以搜索Author的对象,级别7。
@Test
public void givenDB_whenSavingAuthors_thenWeGetOnesWithLevelSeven() {
for (ODocument author : db.browseClass("Author")) author.delete();
ODocument authorOne = new ODocument("Author");
authorOne.field("firstName", "Leo");
authorOne.field("level", 7);
authorOne.save();
ODocument authorTwo = new ODocument("Author");
authorTwo.field("firstName", "Lucien");
authorTwo.field("level", 9);
authorTwo.save();
List<ODocument> result = db.query(
new OSQLSynchQuery<ODocument>("select * from Author where level = 7"));
assertEquals(1, result.size());
}
Likewise, to delete all the records of Author class, we can use:
同样地,要删除Author类的所有记录,我们可以使用。
for (ODocument author : db.browseClass("Author")) {
author.delete();
}
On the OrientDB studio’s BROWSE Tab we can make a query to get all our Author’s objects:
在OrientDB工作室的BROWSE标签上,我们可以进行查询以获得所有的Authors对象。
4.3. Object API
4.3.对象API
OrientDB doesn’t have the object type of database. Thus, the Object API is relying on a Document database.
OrientDB没有对象类型的数据库。因此,对象API依靠的是一个文档数据库。
In Object API type, all other concepts remain the same with only one addition – binding to POJO.
在对象API类型中,所有其他的概念都保持不变,只增加了一个–绑定到POJO。
Let’s start by connecting to the BaeldungDBThree by using the OObjectDatabaseTx class:
让我们首先通过使用OObjectDatabaseTx类连接到BaeldungDBThree。
@BeforeClass
public static void setup() {
String orientDBFolder = System.getenv("ORIENTDB_HOME");
db = new OObjectDatabaseTx("plocal:"
+ orientDBFolder + "/databases/BaeldungDBThree")
.open("admin", "admin");
}
Next, by assuming that the Author is the POJO used to hold an Author data, we need to register it:
接下来,通过假设Author是用来保存Author数据的POJO,我们需要注册它。
db.getEntityManager().registerEntityClass(Author.class);
Author has getters and setters for the following fields:
作者有以下字段的获取器和设置器。
- firstName
- lastName
- level
Let’s create an Author with multi-line instructions if we acknowledged a no-arg constructor:
如果我们承认一个无参数构造函数,让我们用多行指令创建一个Author。
Author author = db.newInstance(Author.class);
author.setFirstName("Luke");
author.setLastName("Sky");
author.setLevel(9);
db.save(author);
On the other hand, if we’ve another constructor that takes the firstName, lastName, and level of the Author respectively, the instantiation is just one line:
另一方面,如果我们有另一个构造函数,分别接收firstName、lastName和level的Author,那么实例化就只有一行。
Author author = db.newInstance(Author.class, "Luke", "Sky", 9);
db.save(author);
The following lines are using to browse and delete all the records of Author class:
下面几行是用来浏览和删除作者类的所有记录。
for (Author author : db.browseClass(Author.class)) {
db.delete(author);
}
To count all authors we just have to provide the class and the database instance without the need to write an SQL query:
要计算所有的作者,我们只需提供类和数据库实例,不需要写SQL查询。
long authorsCount = db.countClass(Author.class);
Similarly, we query authors with level 7 like so:
同样地,我们这样查询具有级别7的作者。
@Test
public void givenDB_whenSavingAuthors_thenWeGetOnesWithLevelSeven() {
for (Author author : db.browseClass(Author.class)) {
db.delete(author);
}
Author authorOne
= db.newInstance(Author.class, "Leo", "Marta", 7);
db.save(authorOne);
Author authorTwo
= db.newInstance(Author.class, "Lucien", "Aurelien", 9);
db.save(authorTwo);
List<Author> result
= db.query(new OSQLSynchQuery<Author>(
"select * from Author where level = 7"));
assertEquals(1, result.size());
}
Finally, this is the official guide that introduces some advanced Object API uses.
最后,这是官方指南,介绍了一些高级Object API的使用。
5. Conclusion
5.结论
In this article, we’ve seen how to use OrientDB as a database management system with its Java APIs. We also learned how to add validation on the fields and write some simple queries.
在这篇文章中,我们已经看到了如何使用OrientDB作为一个数据库管理系统,使用其Java APIs。我们还学习了如何在字段上添加验证,并编写一些简单的查询。
As always, the source code for this article can be found over on GitHub.
像往常一样,本文的源代码可以在GitHub上找到over。