Java访问OrientDB数据库实战教程

OrientDB是开源多模式NoSQL数据库,支持图、文档、key-value、地理空间等多种存储模式;同时支持SQL语法进行查询交互,本文介绍OrientDB数据库的Java api。

安装数据库

首先需要下载最新稳定版本的数据库(本文采用OrientDB3.x)。解压文件至特定目录(使用ORIENTDB_HOME作为数据库主目录),并增加主目录下bin文件夹至环境变量,方便命令行访问。

最后编辑$ORIENTDB_HOME/bin目录下文件orientdb.sh,需要为ORIENTDB_DIR设置ORIENTDB_HOME;为USER_YOU_WANT_ORIENTDB_RUN_WITH设置一个系统用户。

现在OrientDB可以工作了,可以使用orientdb.sh <option>执行命令,其中:

-start: 启动服务
-status: 检查状态
-stop: 停止服务

注意,start和stop动作需要用户密码(orientdb.sh文件中设置)。OrientDB需要Java8或以上版本。

数据库服务启动需要占用2480端口,因此可以访问本地url: http://localhost:2480/studio/index.html

OrientDB Java API安装

有三种不同的API:

  • Graph API : 访问图数据库
  • Document API : 访问文档数据库
  • Obect API : 直接绑定OrientDB Document对象

通过集成使用OrientDB,我们可以在单个代码库中使用所有这些类型。下面看下项目类路径可能需要使用的jar包:

-orientdb-core-.jar: 核心库
-blueprints-core-
.jar: 适配核心组件
-orientdb-graphdb-.jar: 图数据库 API
-orientdb-object-
.jar: 提供对象数据库 API
-orientdb-distributed-.jar: 提供分布式数据库访问数据库集群
-orientdb-tools-
.jar: 下发控制台命令
-orientdb-client-*.jar: 提供远程客户端

maven依赖如下:

<!-- https://mvnrepository.com/artifact/com.orientechnologies/orientdb-core -->
<dependency>
    <groupId>com.orientechnologies</groupId>
    <artifactId>orientdb-core</artifactId>
    <version>3.2.8</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.orientechnologies/orientdb-object -->
<dependency>
    <groupId>com.orientechnologies</groupId>
    <artifactId>orientdb-object</artifactId>
    <version>3.2.8</version>
</dependency>


<!-- https://mvnrepository.com/artifact/com.orientechnologies/orientdb-graphdb -->
<dependency>
    <groupId>com.orientechnologies</groupId>
    <artifactId>orientdb-graphdb</artifactId>
    <version>3.2.8</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.tinkerpop.blueprints/blueprints-core -->
<dependency>
    <groupId>com.tinkerpop.blueprints</groupId>
    <artifactId>blueprints-core</artifactId>
    <version>2.6.0</version>
</dependency>

请检查Maven Central repository ,获取 OrientDB的 Core, GraphDB, Object API以及Blueprints-Core的最新版本。

使用教程

OrientDB使用 TinkerPop Blueprints 实现图数据库。TinkerPop是图计算框架,提供多种方式构建图数据库:

  • Blueprints
  • Pipes
  • Gremlin
  • Rexster
  • Sail Ouplementation

两外,OrientDB支持三种schema,与API类型无关:

  • 完整schema(Schema-Full) :严格模式,在创建类时需要指定所有字段
  • 无schema(scheam-less): 缺省模式,创建类时无需指定属性
  • 混合schema(Schema-Hybrid):上面两种的混合实现,可以指定部分字段,其他字段可自定义

图API

图用于表达网络,包括顶点和边(表示关联)。首先我们在图形界面中创建数据库graphDB,使用admin用户,密码为admin。
在这里插入图片描述

现在连接数据库,需要使用ORIENTDB_HOME环境变量,在安装时已经设置。

@BeforeClass
public static void setup() {
    String orientDBFolder = System.getenv("ORIENTDB_HOME");
    graph = new OrientGraphNoTx("plocal:" + orientDBFolder + 
      "/databases/graphDB", "admin", "admin");
}

下面创建Article, Author 以及Editor类,同时增加必要的属性:

@BeforeClass
public static void init() {
    graph.createVertexType("Article");

    OrientVertexType writerType = graph.createVertexType("Writer");
    writerType.setStrictMode(true);
    writerType.createProperty("firstName", OType.STRING);
    writerType.createProperty("lastName", OType.STRING);
    writerType.createProperty("country", 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");
    vEditor.setProperty("lastName", "Mink's");
    vEditor.setProperty("country", "Cameroon");
    vEditor.setProperty("publicProfile", true);
    vEditor.setProperty("level", "7");

    Vertex vAuthor = graph.addVertex("class:Author");
    vAuthor.setProperty("firstName", "Jerome");
    vAuthor.setProperty("country", "Romania");
    vAuthor.setProperty("publicProfile", false);
    vAuthor.setProperty("level", "3");

    Vertex vArticle = graph.addVertex("class:Article");
    vArticle.setProperty("title", "Introduction to the OrientDB Java APIs.");
    vArticle.setProperty("priority", "High");
    vArticle.setProperty("type", "Article");
    vArticle.setProperty("level", "+L4");

    graph.addEdge(null, vAuthor, vEditor, "has");
    graph.addEdge(null, vAuthor, vArticle, "wrote");
}

在上面代码片段中,对我们数据库简单描述如下:

  • Article 是无结构类,用于定义文章
  • Writer 是完整结构类,其中包括必要的作者信息
  • Author 是 Writer子类,包括更多作者信息
  • Editor 是无结构的Writer子类,包括编辑信息
  • 在保存作者是没有设置lastName字段,但仍出现在图中
  • 关系表示:作者能写文章,但需要有编辑
  • 顶点表示带有一些属性的实体
  • 边是连接两个顶点的实体

注意,如果增加未指定字段给完整结构类,会引发OValidationException异常。运行代码之后,可通过OrientDB studio查看实体关系图。
在这里插入图片描述

下面看如何查询数据库中所有记录(顶点)的数量:

long size = graph.countVertices();

下面代码查看Writer的数量(包括Author和Editor):

@Test
public void givenBaeldungDB_checkWeHaveTwoWriters() {
    long size = graph.countVertices("Writer");

    assertEquals(2, size);
}

查询所有Writer数据:

Iterable<Vertex> writers = graph.getVerticesOfClass("Writer");

查询属性level=7的编辑,仅有一条匹配:

@Test
public void givenBaeldungDB_getEditorWithLevelSeven() {
    String onlyEditor = "";
    for(Vertex v : graph.getVertices("Editor.level", 7)) {
        onlyEditor = v.getProperty("firstName").toString();
    }

    assertEquals("Maxim", onlyEditor);
}

查询顶点时总是需要指定类名称。

文档API

本节使用文档模型。通过记录进行数据操作,记录信息的字段类型可以为文本、图片或二进制格式。通过图形界面创建数据库:docDB:
在这里插入图片描述

与上节一样,也可以使用完整结构、无结构或混合模式结构。数据库连接需要实例化ODatabaseDocumentTx 对象,提供URL和用户凭证:

@BeforeClass
public static void setup() {
    String orientDBFolder = System.getenv("ORIENTDB_HOME");
    db = new ODatabaseDocumentTx("plocal:" 
      + orientDBFolder + "/databases/docDB")
      .open("admin", "admin");
}

首先保存一个包括作者信息的简单文档,我们看到类会被自动创建:

@Test
public void givenDB_whenSavingDocument_thenClassIsAutoCreated() {
    ODocument doc = new ODocument("Author");
    doc.field("name", "Paul");
    doc.save();

    assertEquals("Author", doc.getSchemaClass().getName());
}

相应地查询作者数量:

long size = db.countClass("Author");

我们再次使用字段值查询文档,搜索属性level为7的Author对象:

@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());
}

删除所有作者记录:

for (ODocument author : db.browseClass("Author")) {
    author.delete();
}

对象API

其实OrientDB并没有对象类型,Object API依赖文档数据库。Object API所有概念与文档一致,近增加了绑定对象。

首先连接数据库:

@BeforeClass
public static void setup() {
    String orientDBFolder = System.getenv("ORIENTDB_HOME");
    db = new OObjectDatabaseTx("plocal:" 
      + orientDBFolder + "/databases/objDB")
      .open("admin", "admin");
}

假设Author是pojo,用于容纳Author数据,但需要注册:

db.getEntityManager().registerEntityClass(Author.class);

Author中下面属性有setter和getter方法:

  • firstName
  • lastName
  • level

下面创建author对象:

Author author = db.newInstance(Author.class);
author.setFirstName("Luke");
author.setLastName("Sky");
author.setLevel(9);
db.save(author);

如果有带参数构造函数,可以更简洁创建:

Author author = db.newInstance(Author.class, "Luke", "Sky", 9);
db.save(author);

下面代码浏览并删除Author类记录:

for (Author author : db.browseClass(Author.class)) {
    db.delete(author);
}

依据属性值查询作者信息,无需写SQL查询:

long authorsCount = db.countClass(Author.class);
@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());
}

更新信息可查看官方文档。

总结

本文我们了解了如何使用OrientDB,以及使用Java api访问、管理数据,并通过示例还学习了在不同模式下如何在字段上添加验证并编写一些简单的查询。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值