Instead of SQL, you define your data model by annotating your persistent object types on the programming language level.
ObjectBox - Database Persistence with Entity Annotations
ObjectBox is a database that persists objects, which we sometimes also call entities.
To let ObjectBox know which classes are entities you annotate them with @Entity. This annotation identifies the class User in the following example as a persistable entity. This will trigger ObjectBox to generate persistence code tailored for this class:
@Entity\npublicclassUser{\n\n@Id\nprivatelong id;\n\nprivateString name;\n\n // Not persisted:\n@Transient\nprivateint tempUsageCount;\n\n // TODO: getters and setters.\n}
Note:
It’s often good practice to model entities as “dumb” data classes (POJOs) with just properties.
Entities must have a no-args constructor, or for better performance, a constructor with all properties as arguments. In the above example, a default, no-args constructor is generated by the compiler.
@Entity\ndataclassUser(\n@Idvar id: Long=0,\nvar name: String? =null,\n// Not persisted:\n@Transientvar tempUsageCount: Int=0\n)
Note:
It’s often good practice to model entities as “dumb” data classes (POJOs) with just properties.
Entities must have a no-args constructor, or for better performance, a constructor with all properties as arguments. In the above example, a default, no-args constructor is generated by the compiler.\nFor Kotlin data classes this can be achieved by adding default values for all parameters. (Technically this is only required if adding properties to the class body, like custom or transient properties or relations, but it's a good idea to do it always.)
@Entity()\nclass User {\n // Annotate with @Id() if name isn't \"id\" (case insensitive).\n int id = 0;\n String? name;\n \n // Not persisted:\n @Transient\n int tempUsageCount = 0;\n)
It’s often good practice to model entities as “dumb” data classes with just properties.
For ObjectBox to be able to construct objects read from the database, entities must have a no-args constructor or a constructor with argument names matching the properties, for example:
User({this.id, this.name});
@Entity()\nclass User:\n id = Id\n name = String\n temp_usage_count = None
Available Property types include: Bool, Char, Bytes, String, Int8/16/32/64, Float32/64 *Vector and *List variants (e.g. Float32Vector)
Object IDs: @Id
In ObjectBox, entities must have one 64-bit integer ID property with non-private visibility (or non-private getter and setter method) to efficiently get or reference objects.
@Entity\npublicclassUser{\n@Idpubliclong id;\n // Note: You can use the nullable java.lang.Long, but we do not recommend it.\n\n...\n}
@Entity\ndata class User(\n @Id var id: Long = 0,\n ...\n)
@Entity()\nclass User {\n // Annotate with @Id() if name isn't \"id\" (case insensitive).\n int id;\n\n ...\n}
@Entity()\nclass User:\n id = Id # Use either class Id or instance notation (e.g. Id())
If you need to use another type for IDs (such as a string UID given by a server), model them as regular properties and use queries to look up objects by your application-specific ID. Also, make sure to index the property, and if it's a string use a case-sensitive condition, to speed up lookups. To prevent duplicates it is also possible to enforce a unique value for this secondary ID.
@Entity\nclass StringIdEntity {\n @Id public long id;\n @Index public String uid;\n // Alternatively:\n // @Unique String uid;\n}\n\nStringIdEntity entity = box.query()\n .equal(StringIdEntity_.uid, uid, StringOrder.CASE_SENSITIVE)\n .build().findUnique()
@Entity\ndata class StringIdEntity(\n @Id var id: Long = 0,\n @Index var uid: String? = null\n // Alternatively:\n // @Unique uid: String? = null\n)\n\nval entity = box.query()\n .equal(StringIdEntity_.uid, uid, StringOrder.CASE_SENSITIVE)\n .build().findUnique()
@Entity()\nclass StringIdEntity(\n int id;\n \n @Index() // or alternatively use @Unique()\n String uid;\n)\n\nfinal objects = box.query(StringIdEntity_.uid.equals('...')).build().find();
ID properties are unique and indexed by default.
When you put a new object you do not assign an ID. By default IDs for new objects are assigned by ObjectBox. See the page on Object IDs for details.
ObjectBox needs to access the data of your entity’s properties (e.g. in the generated code). You have two options:
Make sure properties do not have private visibility.
Provide standard getters (your IDE can generate them easily).
To improve performance when ObjectBox constructs your entities, you might also want to provide an all-properties constructor.
@Entity\npublic class Order {\n \n // Option 1: field is not private.\n @Id long id;\n \n // Option 2: field is private, but getter is available.\n private String name;\n \n public ToOne<Customer> customer;\n public ToMany<Order> relatedOrders;\n \n // At minimum, provide a default constructor for ObjectBox.\n public Order() {\n }\n\n // Optional: all-properties constructor for better performance.\n // - make sure type matches exactly,\n // - for ToOne add its virtual ID property instead,\n // - for ToMany add no parameter.\n public Order(long id, String name, long customerId) {\n this.id = id;\n this.name = name;\n this.customer.setTargetId(customerId);\n }\n \n public String getName() {\n return this.name;\n }\n}
// For Kotlin a data class with default values\n// meets all above requirements. \n@Entity\ndata class User(\n @Id var id: Long = 0,\n var name: String? = null\n)
@Entity()\nclass User {\n int id;\n \n String? _name;\n \n String get name {...}\n \n set name(String value) {...}\n \n User(this.id);\n}
Supported property types
ObjectBox supports a wide range of property types including integers, floats, strings, dates, lists, and flex properties for dynamic data. See the dedicated page for details:
@Transient marks properties that should not be persisted. In Java static or transient properties will also not be persisted.
@Transient\nprivate int notPersisted;
@Transient\nvar notPersisted: Int = 0
@Transient()\nint? notPersisted;
NameInDb
Only available for Java/Kotlin at the moment
@NameInDb lets you define a name on the database level for a property. This allows you to rename the property without affecting the property name on the database level.
@NameInDb only works with inline constants to specify a column name.
@NameInDb(\"username\")\nprivate String name;
@NameInDb(\"username\")\nvar name: String? = null
Property Indexes
Annotate a property with @Index to create a database index for the corresponding database column. This can improve performance when querying for that property.
@Index\nprivate String name;
@Index is currently not supported for String[], byte[], float and double
@Index\nvar name: String? = null
@Index is currently not supported for Array<String>, ByteArray , Float and Double
@Index()\nString name;
@Index is currently not supported for double and listsList<String>, List<int>, Uint8List, Int8List
@Entity()\nclass User:\n name = String(index=Index())
An index stores additional information in the database to make lookups faster. As an analogy, we could look at Java-like programming languages where you store objects in a list. For example, you could store persons using a List<Person>. Now, you want to search for all persons with a specific name so you would iterate through the list and check for the name property of each object. This is an O(N) operation and thus doesn't scale well with an increasing number of objects. To make this more scalable you can introduce a second data structure Map<String, Person> with the name as a key. This will give you a constant lookup time (O(1)). The downside of this is that it needs more resources (here: RAM) and slows down add/remove operations on the list a bit. These principles can be transferred to database indexes, just that the primary resource consumed is disk space.
Index types (String)
For scalar properties, ObjectBox uses a value-based index. Because String properties typically require more storage space than scalar values, by default ObjectBox uses a hash index for strings instead.
To override the default and use a value-based index for a String property, specify the index type:
Keep in mind that for String, depending on the length of your values, a value-based index may require more storage space than the default hash-based index.
ObjectBox supports these index types:
Not specified or DEFAULT Uses the best index based on property type (HASH for String, VALUE for others).
VALUE Uses property values to build the index. For String, this may require more storage than a hash-based index.
HASH Uses a 32-bit hash of property values to build the index. Occasional collisions may occur which should not have any performance impact in practice. Usually, a better choice than HASH64, as it requires less storage.
HASH64 Uses a 64-bit hash of property values to build the index. Requires more storage than HASH and thus should not be the first choice in most cases.
Limits of hash-based indexes: Hashes work great for equality checks, but not for \"starts with\" type conditions. If you frequently use those, you should use value-based indexes instead.
Vector Index for Nearest Neighbor Search
To enable nearest neighbor search, a special index type for vector properties is available:
The REPLACE strategy will add a new object with a different ID. As relations (ToOne/ToMany) reference objects by ID, if the previous object was referenced in any relations, these need to be updated manually.
Unique constraints are based on an index, so it is possible to further configure the index with an @Index annotation.
Change database type
Use @Type in Java/Kotlin or the type attribute on @Property in Dart to override how the value of a property is stored and interpreted in the database.
// Store 64-bit integer as time in nanoseconds.\n@Type(DatabaseType.DateNano)\nprivate long timeInNanos;
// Store 64-bit integer as time in nanoseconds.\n@Type(DatabaseType.DateNano)\nvar timeInNanos: Long = 0
This site uses cookies to deliver its service and to analyze traffic. By browsing this site, you accept the privacy policy.
",
"metadata": {
"apple-mobile-web-app-status-bar-style": "default",
"apple-mobile-web-app-title": "ObjectBox Docs",
"color-scheme": "light",
"description": "Instead of SQL, you define your data model by annotating your persistent object types on the programming language level.",
"generator": "GitBook (59ffb95)",
"lang": "en",
"mobile-web-app-capable": "yes",
"next-size-adjust": "",
"og:description": "Instead of SQL, you define your data model by annotating your persistent object types on the programming language level.",
"og:image": "https://docs.objectbox.io/~gitbook/ogimage/-LEUYsjP1BaBoJ_OPUD3",
"og:title": "Entity Annotations | ObjectBox Docs",
"robots": "index, follow",
"twitter:card": "summary_large_image",
"twitter:description": "Instead of SQL, you define your data model by annotating your persistent object types on the programming language level.",
"twitter:image": "https://docs.objectbox.io/~gitbook/ogimage/-LEUYsjP1BaBoJ_OPUD3",
"twitter:title": "Entity Annotations | ObjectBox Docs",
"viewport": "width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover"
},
"title": "Entity Annotations | ObjectBox Docs",
"url": "https://docs.objectbox.io/entity-annotations",
"usage": {
"tokens": 221469
}
},
"meta": {
"usage": {
"tokens": 221469
}
},
"status": 20000
}