bfour bfour - 2 years ago 158
Java Question

How do I create an auto-incrementing index/a sequence for an OrientDB database using the Java Document API?

I am using OrientDB with Java via its Document API. I have a simple Class called

which has an attribute
. I explicitly declare the schema like this:

OSchema schema = db.getMetadata().getSchema();
OClass itemsClass = schema.createClass("items");
itemsClass.createProperty("ID", OType.LONG);

and then create an index on

Now when I create a new item (something like
ODocument doc = new ODocument("items")
etc.), I would like the ID for the new item to be generated on the database (something like a sequence in RDBMS).
How do I do this with the Java Document API for OrientDB?

Answer Source

OrientDB doesn't support serial (we've an issue for that), so you can manage your own counter in this way (example using SQL):

create class counter
insert into counter set name='mycounter', value=0

And then every time you need a new number you can do:

update counter incr value = 1 where name = 'mycounter'

This works in a SQL batch in this way:

let $counter = update counter incr value = 1 where name = 'mycounter' return after
insert into items set id = $counter.value, qty = 10, price = 1000

By using Java you can make the same: create singleton class "Counters" that everytime increment the document value and save it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download