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

爷,独闯天下 提交于 2020-01-23 12:07:21

问题


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?


回答1:


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.




回答2:


Starting from OrientDB 2.2 Sequences are now supported

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



来源:https://stackoverflow.com/questions/24816489/how-do-i-create-an-auto-incrementing-index-a-sequence-for-an-orientdb-database-u

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!