ObjectBox - Database Persistence with Entity Annotations

ObjectBox is a database that persists objects. For a clear distinction, we sometimes call those persistable objects entities. To let ObjectBox know which classes are entities you can either make them implement the ObjectBox.Entity protocol, or add annotations to them. Then ObjectBox can do its magic with your entities.

Here is an example:

// sourcery: Entity
class User {
var id: Id<User> = 0 // sourcery: entityId
var name: String
// sourcery: transient
private var tempUsageCount: Int // not persisted
// ...
}

The Entity annotation identifies the Swift class User as a persistable entity. This will trigger ObjectBox to generate persistence code tailored for this class, even if it does not conform to the Entity protocol..

Note:

  • It’s often good practice to model entities as “dumb” data classes with just properties.

Transient

// sourcery: Entity
public class User {
// sourcery: transient
var tempUsageCount: Int
// ...
}

The transient annotation marks properties that should not be persisted, like the temporary counter above. As far as ObjectBox is concerned, transient properties simply do not exist.

Object IDs: entityId

In ObjectBox, every object has an ID of type Id<> to efficiently get or reference objects. Usually ObjectBox will just find that property in your entity based on its type and "do the right thing", but if you have several properties of the same Id<> type, you can use an annotation to mark a particular property as the ID of your entity:

class User: Entity {
// sourcery: objectId
var id: Id<User> = 0
// ...
}

Relations

Creating to-one and to-many relations between objects is possible as well, see the Relations documentation for details.

Triggering generation

You usually should not need to do anything special to trigger code generation once your entity classes are properly annotated. The setup.rb script should have automatically configured your project to run the code generator when you compile your project, for example using Product > Build in Xcode.