Explanation of Object IDs and how they are used and assigned in ObjectBox.
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.
longIDs 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 of whether an entity is new (zero) or already persisted (non-zero). This is used internally, e.g. for relations that heavily rely on IDs.
Object IDs may be any
longvalue, with two exceptions:
- 0 (zero): Objects with an ID of zero (and
nullif 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.
Also, note that this will mean in some circumstances IDs from deleted objects may be reused. So it is best to not rely on a specific ID getting assigned.
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.
If your code needs to assign IDs by itself you can change the
@Id(assignable = true)
int id = 0;
This will allow putting an entity with any valid ID (see Special Object IDs). If the
@Idfield is writable, it can still be set to zero to let ObjectBox auto-assign a new ID.
Warning: self-assigned IDs break automatic state detection (new vs. persisted entity based on the ID). Therefore, you should put entities with self-assigned IDs immediately and may have to attach the box manually, especially when working with relations.