1. Overview

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.

In this article, we’ll cover the setup and use the OrientDB Java APIs.

2. Installation

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).

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.

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.

Now we’ve got a fully working OrientDB. We can use the orientdb.sh script with options:

  • start: to start the server
  • status: to check the 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).

Once the server is launched, it’ll occupy the port 2480. Therefore we can access it locally using this URL:

orientdb running

More details of manual installation can be found here.

Note: OrientDB requires Java version 1.7 or higher.

Previous versions are available here.

3. OrientDB Java APIs Setup

orientdb document

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

To count all authors we just have to provide the class and the database instance without the need to write an SQL query:

long authorsCount = db.countClass(Author.class);

Similarly, we query authors with level 7 like so:

@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.

5. Conclusion

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.

As always, the source code for this article can be found over on GitHub.