Object API

Object API - 图1 Object API allows to work with POJOs that bind OrientDB documents. This API is not able work on top of Graph-API. If you are interested on using a Object-Graph mapping framework, look at the available ones that work on top of Graph-API layer: Object-Graph Mapping.

Requirements

To use the Object APi include the following jars in your classpath:

  1. orientdb-core-*.jar
  2. orientdb-object-*.jar

If you’re using the Object Database interface connected to a remote server (not local/embedded mode) include also:

  1. orientdb-client-*.jar
  2. orientdb-enterprise-*.jar

Introduction

The OrientDB Object Interface works on top of the Document-Database and works like an Object Database: manages Java objects directly. It uses the Java Reflection to register the classes and Javassist tool to manage the Object-to-Document conversion. Please consider that the Java Reflection in modern Java Virtual Machines is really fast and the discovering of Java meta data is made only at first time.

Future implementation could use also the byte-code enhancement techniques in addition.

The proxied objects have a ODocument bounded to them and transparently replicate object modifications. It also allows lazy loading of the fields: they won’t be loaded from the document until the first access. To do so the object MUST implement getters and setters since the Javassist Proxy is bounded to them. In case of object load, edit an update all non loaded fields won’t be lost.

The database instance has an API to generate new objects already proxied, in case a non-proxied instance is passed it will be serialized, wrapped around a proxied instance and returned.

Read more about the Binding between Java Objects and Records.

Quick example of usage:

  1. // OPEN THE DATABASE
  2. OObjectDatabaseTx db = new OObjectDatabaseTx ("remote:localhost/petshop").open("admin", "admin");
  3. // REGISTER THE CLASS ONLY ONCE AFTER THE DB IS OPEN/CREATED
  4. db.getEntityManager().registerEntityClasses("foo.domain");
  5. // CREATE A NEW PROXIED OBJECT AND FILL IT
  6. Account account = db.newInstance(Account.class);
  7. account.setName( "Luke" );
  8. account.setSurname( "Skywalker" );
  9. City rome = db.newInstance(City.class,"Rome", db.newInstance(Country.class,"Italy"));
  10. account.getAddresses().add(new Address("Residence", rome, "Piazza Navona, 1"));
  11. db.save( account );
  12. // CREATE A NEW OBJECT AND FILL IT
  13. Account account = new Account();
  14. account.setName( "Luke" );
  15. account.setSurname( "Skywalker" );
  16. City rome = new City("Rome", new Country("Italy"));
  17. account.getAddresses().add(new Address("Residence", rome, "Piazza Navona, 1"));
  18. // SAVE THE ACCOUNT: THE DATABASE WILL SERIALIZE THE OBJECT AND GIVE THE PROXIED INSTANCE
  19. account = db.save( account );

Connection Pool

One of most common use case is to reuse the database avoiding to create it every time. It’s also the typical scenario of the Web applications.

  1. // OPEN THE DATABASE
  2. OObjectDatabaseTx db= OObjectDatabasePool.global().acquire("remote:localhost/petshop", "admin", "admin");
  3. // REGISTER THE CLASS ONLY ONCE AFTER THE DB IS OPEN/CREATED
  4. db.getEntityManager().registerEntityClass("org.petshop.domain");
  5. try {
  6. ...
  7. } finally {
  8. db.close();
  9. }

The close() method doesn’t close the database but release it to the owner pool. It could be reused in the future.

Database URL

In the example above a database of type Database Object Transactional has been created using the storage: remote:localhost/petshop. This address is a URL. To know more about database and storage types go to Database URL.

In this case the storage resides in the same computer of the client, but we’re using the remote storage type. For this reason we need a OrientDB Server instance up and running. If we would open the database directly bypassing the server we had to use the local storage type such as “plocal:/usr/local/database/petshop/petshop” where, in this case, the storage was located in the /usr/local/database/petshop folder on the local file system.

Multi-threading

The OObjectDatabaseTx class is non thread-safe. For this reason use different OObjectDatabaseTx instances by multiple threads. They will share local cache once transactions are committed.

Inheritance

Starting from the release 0.9.19 OrientDB supports the Inheritance. Using the ObjectDatabase the inheritance of Documents fully matches the Java inheritance.

When registering a new class Orient will also generate the correct inheritance schema if not already generated.

Example:

  1. public class Account {
  2. private String name;
  3. // getters and setters
  4. }
  5. public class Company extends Account {
  6. private int employees;
  7. // getters and setters
  8. }

When you save a Company object, OrientDB will save the object as unique Document in the cluster specified for Company class. When you search between all the Account instances with:

  1. SELECT FROM account

The search will find all the Account and Company documents that satisfy the query.

Use the database

Before to use a database you need to open or create it:

  1. // CREATE AN IN MEMORY DATABASE
  2. OObjectDatabaseTx db1 = new OObjectDatabaseTx("memory:petshop").create();
  3. // OPEN A REMOTE DATABASE
  4. OObjectDatabaseTx db2 = new OObjectDatabaseTx("remote:localhost/petshop").open("admin", "admin");

The database instance will share the connection versus the storage. if it’s a local storage, then all the database instances will be synchronized on it. If it’s a remote storage then the network connection will be shared among all the database instances.

To get the reference to the current user use:

  1. OUser user = db.getUser();

Once finished remember to close the database to free precious resources.

  1. db.close();

Working with POJO

Please read the POJO binding guide containing all the information about the management of POJO.

Work in schema-less mode

The Object Database can be used totally in schema-less mode as long as the POJO binding guide requirements are followed. Schema less means that the class must be created but even without properties. Take a look to this example:

  1. OObjectDatabaseTx db = new OObjectDatabaseTx("remote:localhost/petshop").open("admin", "admin");
  2. db.getEntityManager().registerEntityClass(Person.class);
  3. Person p = db.newInstance(Person.class);
  4. p.setName( "Luca" );
  5. p.setSurname( "Garulli" );
  6. p.setCity( new City( "Rome", "Italy" ) );
  7. db.save( p );
  8. db.close();

This is the very first example. While the code it’s pretty clear and easy to understand please note that we didn’t declared “Person” structure before now. However Orient has been able to recognize the new object and save it in persistent way.

Work in schema-full mode

In the schema-full mode you need to declare the classes you’re using. Each class contains one or multiple properties. This mode is similar to the classic Relational DBMS approach where you need to create tables before storing records. To work in schema-full mode take a look at the Schema APIs page.

Create a new object

The best practice to create a Java object is to use the OObjectDatabaseTx.newInstance() API:

  1. public class Person {
  2. private String name;
  3. private String surname;
  4. public Person(){
  5. }
  6. public Person(String name){
  7. this.name = name;
  8. }
  9. public Person(String name, String surname){
  10. this.name = name;
  11. this.surname = surname;
  12. }
  13. // getters and setters
  14. }
  15. OObjectDatabaseTx db = new OObjectDatabaseTx("remote:localhost/petshop").open("admin", "admin");
  16. db.getEntityManager().registerEntityClass(Person.class);
  17. // CREATES A NEW PERSON FROM THE EMPTY CONSTRUCTOR
  18. Person person = db.newInstance(Person.class);
  19. person.setName( "Antoni" );
  20. person.setSurname( "Gaudi" );
  21. db.save( person );
  22. // CREATES A NEW PERSON FROM A PARAMETRIZED CONSTRUCTOR
  23. Person person = db.newInstance(Person.class, "Antoni");
  24. person.setSurname( "Gaudi" );
  25. db.save( person );
  26. // CREATES A NEW PERSON FROM A PARAMETRIZED CONSTRUCTOR
  27. Person person = db.newInstance(Person.class,"Antoni","Gaudi");
  28. db.save( person );

However any Java object can be saved by calling the db.save() method, if not created with the database API will be serialized and saved. In this case the user have to assign the result of the db.save() method in order to get the proxied instance, if not the database will always treat the object as a new one. Example:

  1. // REGISTER THE CLASS ONLY ONCE AFTER THE DB IS OPEN/CREATED
  2. db.getEntityManager().registerEntityClass(Animal.class);
  3. Animal animal = new Animal();
  4. animal.setName( "Gaudi" );
  5. animal.setLocation( "Madrid" );
  6. animal = db.save( animal );

Note that the behaviour depends by the transaction begun if any. See Transactions.

Browse all the records in a cluster

  1. for (Object o : database.browseCluster("CityCars")) {
  2. System.out.println( ((Car) o).getModel() );

Browse all the records of a class

  1. for (Animal animal : database.browseClass(Animal.class)) {
  2. System.out.println( animal.getName() );

Count records of a class

  1. long cars = database.countClass("Car");

Count records of a cluster

  1. long cityCars = database.countCluster("CityCar");

Update an object

Any proxied object can be updated using the Java language and then calling the db.save() method to synchronize the changes to the repository. Behaviour depends by the transaction begun if any. See Transactions.

  1. animal.setLocation( "Nairobi" );
  2. db.save( animal );

Orient will update only the fields really changed.

Example of how to update the price of all the animals by 5% more:

  1. for (Animal animal : database.browseClass(Animal.class)) {
  2. animal.setPrice(animal.getPrice() * 105 / 100);
  3. database.save(animal);
  4. }

If the db.save() method is called with a non-proxied object the database will create a new document, even if said object were already saved

Delete an object

To delete an object call the db.delete() method on a proxied object. If called on a non-proxied object the database won’t do anything. Behaviour also depends by the transaction begun if any. See Transactions.

  1. db.delete( animal );

Example of deletion of all the objects of class “Animal”.

  1. for (Animal animal : database.browseClass(Animal.class))
  2. database.delete(animal);

Cascade deleting

Object Database uses JPA annotations to manage cascade deleting. It can be done expliciting (orphanRemoval = true) or using the CascadeType. The first mode works only with @OneToOne and @OneToMany annotations, the CascadeType works also with @ManyToMany annotation.

Example:

  1. public class JavaCascadeDeleteTestClass {
  2. ...
  3. @OneToOne(orphanRemoval = true)
  4. private JavaSimpleTestClass simpleClass;
  5. @ManyToMany(cascade = { CascadeType.REMOVE })
  6. private Map<String, Child> children = new HashMap<String, Child>();
  7. @OneToMany(orphanRemoval = true)
  8. private List<Child> list = new ArrayList<Child>();
  9. @OneToMany(orphanRemoval = true)
  10. private Set<Child> set = new HashSet<Child>();
  11. ...
  12. // GETTERS AND SETTERS
  13. }

so calling

  1. database.delete(testClass);

or

  1. for (JavaCascadeDeleteTestClass testClass : database.browseClass(JavaCascadeDeleteTestClass.class))
  2. database.delete(testClass);

will also delete JavaSimpleTestClass instances contained in “simpleClass” field and all the other documents contained in “children”,”list” and “test”

Attaching and Detaching

Since version 1.1.0 the Object Database provides attach(Object) and detach(Object) methods to manually manage object to document data transfer.

Attach

With the attach method all data contained in the object will be copied in the associated document, overwriting all existing informations.

  1. Animal animal = database.newInstance(Animal.class);
  2. animal.name = "Gaudi" ;
  3. animal.location = "Madrid";
  4. database.attach(animal);
  5. database.save(animal);

in this way all changes done within the object without using setters will be copied to the document.

There’s also an attachAndSave(Object) methods that after attaching data saves the object.

  1. Animal animal = database.newInstance(Animal.class);
  2. animal.name = "Gaudi" ;
  3. animal.location = "Madrid";
  4. database.attachAndSave(animal);

This will do the same as the example before

Detach

With the detach method all data contained in the document will be copied in the associated object, overwriting all existing informations. The detach(Object) method returns a proxied object, if there’s a need to get a non proxied detached instance the detach(Object,boolean) can be used.

  1. Animal animal = database.load(rid);
  2. database.detach(animal);

this will copy all the loaded document information in the object, without needing to call all getters. This methods returns a proxied instance

  1. Animal animal = database.load(rid);
  2. animal = database.detach(animal,true);

this example does the same as before but in this case the detach will return a non proxied instance.

Since version 1.2 there’s also the detachAll(Object, boolean) method that detaches recursively the entire object tree. This may throw a StackOverflowError with big trees. To avoid it increase the stack size with -Xss java option. The boolean parameter works the same as with the detach() method.

  1. Animal animal = database.load(rid);
  2. animal = database.detachAll(animal,true);

Lazy detachAll

(Since 2.2)

When calling detachAll(object,true) on a large object tree, the call may become slow, especially when working with remote connections. It will recurse through every link in the tree and load all dependencies.

To only load parts of the object tree, you can add the @OneToOne(fetch=FetchType.LAZY) annotation like so:

  1. public class LazyParent {
  2. @Id
  3. private String id;
  4. @OneToOne(fetch = FetchType.LAZY)
  5. private LazyChild child;
  6. ...
  7. public class LazyChild {
  8. @Id
  9. private ORID id;
  10. private String name;
  11. public ORID getId() {
  12. return id;
  13. }
  14. public void setId(ORID id) {
  15. this.id = id;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. }

In the above example, when calling detachAll(lazyParent,true), the child variable (if a link is available) will contain a normal LazyChild object, but only with the id loaded. So the name property will be null, as will any other property that is added to the class. The id object can be used to load the LazyChild object in a later stage.

Execute a query

Although OrientDB is part of NoSQL databases, supports the SQL engine, or at least a subset of it with such extensions to work with objects and graphs.

To know more about the SQL syntax supported go to: SQL-Query.

Example:

  1. List<Animal> result = db.query(
  2. new OSQLSynchQuery<Animal>("select * from Animal where ID = 10 and name like 'G%'"));

Right usage of the graph

OrientDB is a graph database. This means that traversing is very efficient. You can use this feature to optimize queries. A common technique is the Pivoting.

SQL Commands

To execute SQL commands use the command() method passing a OCommandSQL object:

  1. int recordsUpdated = db.command(
  2. new OCommandSQL("UPDATE Animal SET sold = false")).execute();

See all the SQL Commands.

Get the ODocument from a POJO

The OObjectDatabaseTx implementation has APIs to get a document from its referencing object:

  1. ODocument doc = db.getRecordByUserObject( animal );

In case of non-proxied objects the document will be a new generated one with all object field serialized in it.

Get the POJO from a Record

The Object Database can also create an Object from a record.

  1. Object pojo = db.getUserObjectByRecord(record);

Schema Generation

Since version 1.5 the Object Database manages automatic Schema generation based on registered entities. This operation can be

  • manual
  • automatic

The ObjectDatabase will generate class properties based on fields declaration if not created yet.

Changes in class fields (as for type changing or renaming) types won’t be updated, this operation has to be done manually

Manual Schema Generation

Schema can be generated manually for single classes or entire packages:

Version 1.6

  1. db.getMetadata().getSchema().generateSchema(Foo.class); // Generates the schema for Foo class
  2. db.getMetadata().getSchema().generateSchema("com.mycompany.myapp.mydomainpackage"); // Generates the schema for all classes contained in the given package

Version 1.5

  1. db.generateSchema(Foo.class); // Generates the schema for Foo class
  2. db.generateSchema("com.mycompany.myapp.mydomainpackage"); // Generates the schema for all classes contained in the given package

Automatic Schema Generation

By setting the “automaticSchemaGeneration” property to true the schema will be generated automatically on every class declaration.

  1. db.setAutomaticSchemaGeneration(true);
  2. db.getEntityManager().registerClass(Foo.class); // Generates the schema for Foo class after registering.
  3. db.getEntityManager().registerEntityClasses("com.mycompany.myapp.mydomainpackage"); // Generates the schema for all classes contained in the given package after registering.

class Foo could look like, generating one field with an Integer and ignoring the String field.

  1. public class Foo {
  2. private transient String field1; // ignore this field
  3. private Integer field2; // create a Integer
  4. }

Standard schema management equivalent

Having the Foo class defined as following

  1. public class Foo{
  2. private String text;
  3. private Child reference;
  4. private int number;
  5. //getters and setters
  6. }

schema generation will create “text”, “reference” and “number” properties as respectively STRING, LINK and INTEGER types.

The default schema management API equivalent would be

  1. OClass foo = db.getMetadata().getSchema().getClass(Foo.class);
  2. OClass child = db.getMetadata().getSchema().getClass(Child.class)
  3. foo.createProperty("text",OType.STRING);
  4. foo.createProperty("number",OType.INTEGER);
  5. foo.createProperty("text",OType.LINK, child);
  6. db.getMetadata().getSchema().save();

Schema synchronizing

Since version 1.6 there’s an API to synchronize schema of all registered entities.

  1. db.getMetadata().getSchema().synchronizeSchema();

By calling this API the ObjectDatabase will check all registered entities and generate the schema if not generated yet. This management is useful on multi-database enviroments


Old Implementation ODatabaseObjectTx

Until the release 1.0rc9 the Object Database was implemented as the class com.orientechnologies.orient.db.object.ODatabaseObjectTx. This class is deprecated, but if you want to continue to use it change the package to: com.orientechnologies.orient.object.db.

Introduction

This implementation and documentation refers to all ODatabaseObjectXXX deprecated classes.

The Orient Object DB works on top of the Document-Database and it’s able to treat Java objects without the use of pre-processor, byte enhancer or Proxy classes. It uses the simpler way: the Java Reflection. Please consider that the Java reflection in modern Java Virtual Machines is really fast and the discovering of Java meta data is made at first time. Future implementation could use the byte-code enhancement techniques in addition.

Read more about the Binding between Java Objects and Records.

Quick example of usage:

  1. // OPEN THE DATABASE
  2. ODatabaseObjectTx db = new ODatabaseObjectTx ("remote:localhost/petshop").open("admin", "admin");
  3. db.getEntityManager().registerEntityClasses("foo.domain");
  4. // CREATE A NEW ACCOUNT OBJECT AND FILL IT
  5. Account account = new Account()
  6. account.setName( "Luke" );
  7. account.setSurname( "Skywalker" );
  8. City rome = new City("Rome", new Country("Italy"));
  9. account.getAddresses().add(new Address("Residence", rome, "Piazza Navona, 1"));
  10. db.save( account );

Connection Pool

One of most common use case is to reuse the database avoiding to create it every time. It’s also the typical scenario of the Web applications.

  1. // OPEN THE DATABASE
  2. ODatabaseObjectTx db= ODatabaseObjectPool.global().acquire("remote:localhost/petshop", "admin", "admin");
  3. ...
  4. db.close();

The close() method doesn’t close the database but release it to the owner pool. It could be reused in the future.

Inheritance

Starting from the release 0.9.19 OrientDB supports the Inheritance. Using the ObjectDatabase the inheritance of Documents fully matches the Java inheritance.

Example:

  1. public class Account {
  2. private String name;
  3. }
  4. public class Company extends Account {
  5. private int employees;
  6. }

When you save a Company object, OrientDB will save the object as unique Document in the cluster specified for Company class. When you search between all the Account instances with:

  1. SELECT FROM account

The search will find all the Account and Company documents that satisfy the query.