bfour
bfour

Reputation: 160

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 items which has an attribute ID. 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 ID: CREATE INDEX items.ID ON items (ID) UNIQUE.

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?

Upvotes: 2

Views: 2014

Answers (2)

Solido
Solido

Reputation: 31

Starting from OrientDB 2.2 Sequences are now supported

http://orientdb.com/docs/2.2/Sequences-and-auto-increment.html

Upvotes: 1

Lvca
Lvca

Reputation: 9060

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:

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

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

Upvotes: 6

Related Questions