Objects must have an ID property of type
long. You are free to use the wrapper type
java.lang.Long, but we advise against it in most cases.
long IDs are enforced to make ObjectBox very efficient internally.
If your application requires other ID types (such as a string UID given by a server), you can model them as standard properties and use queries to look up entities by your application specific ID.
When you create new entity objects (on the language level), they are not persisted yet and their ID is (zero). Once an entity is put (persisted), ObjectBox will assign an ID to the entity. You can access the ID property right after the call to
Those are also applied the other way round: ObjectBox uses the ID as a state indication whether an entity is new (zero) or already persisted (non-zero). This is used internally, e.g. for relations which heavily rely on IDs.
Object IDs may be any
long value, with two exceptions:
0 (zero): Objects with an ID of zero (and
null if the ID is of type
Long) are considered new (not persisted before). Putting such an object will always insert a new object and assign an unused ID to it.
0xFFFFFFFFFFFFFFFF (-1 in Java): This value is reserved for internal use by ObjectBox and may not be used by the app.
By default object IDs are assigned by ObjectBox. For each new object, ObjectBox will assign an unused ID that is above the current highest ID value used in a box. For example, if there are two objects with ID 1 and ID 100 in a box the next object that is put will be assigned ID 101.
By default, only ObjectBox may assign IDs. If you try to put an object with an ID greater than the currently highest ID, ObjectBox will throw an error.
However, if you need to assign IDs by yourself you can change the ID annotation to
@Id(assignable =true) . This will allow putting an entity with any valid ID, including zero to let ObjectBox auto assign a new ID.
Attention: self-assigned IDs require you to make some adjustments as they break the state detection (new vs. persisted entity based on the ID). Thus, you should put entities with self-assigned IDs to restore the state sematics asap, especially when working with relations.
Check this issue on Github for status.