Entity Annotations
ObjectBox database persistence for Java is based on objects for object-oriented programming instead of SQL. Learn how to persist entities with entity annotations in this tutorial section.

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 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:
Java
Kotlin
Dart
1
@Entity
2
public class User {
3
4
@Id
5
private long id;
6
7
private String name;
8
9
// Not persisted:
10
@Transient
11
private int tempUsageCount;
12
13
// TODO: getters and setters.
14
}
Copied!
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.
1
@Entity
2
data class User(
3
@Id var id: Long = 0,
4
var name: String? = null,
5
// Not persisted:
6
@Transient var tempUsageCount: Int = 0
7
)
Copied!
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. For 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.)
1
@Entity()
2
class User {
3
// Annotate with @Id() if name isn't "id" (case insensitive).
4
int id = 0;
5
String? name;
6
7
// Not persisted:
8
@Transient
9
int tempUsageCount = 0;
10
)
Copied!
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:
1
User({this.id, this.name});
Copied!

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.
Java
Kotlin
Dart
1
@Entity
2
public class User {
3
@Id public long id;
4
// Note: You can use the nullable java.lang.Long, but we do not recommend it.
5
6
...
7
}
Copied!
1
@Entity
2
data class User(
3
@Id var id: Long = 0,
4
...
5
)
Copied!
1
@Entity()
2
class User {
3
// Annotate with @Id() if name isn't "id" (case insensitive).
4
int id;
5
6
...
7
}
Copied!
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.
Java
Kotlin
Dart
1
@Entity
2
class StringIdEntity {
3
@Id public long id;
4
@Index public String uid;
5
// Alternatively:
6
// @Unique String uid;
7
}
8
9
StringIdEntity entity = box.query()
10
.equal(StringIdEntity_.uid, uid, StringOrder.CASE_SENSITIVE)
11
.build().findUnique()
Copied!
1
@Entity
2
data class StringIdEntity(
3
@Id var id: Long = 0,
4
@Index var uid: String? = null
5
// Alternatively:
6
// @Unique uid: String? = null
7
)
8
9
val entity = box.query()
10
.equal(StringIdEntity_.uid, uid, StringOrder.CASE_SENSITIVE)
11
.build().findUnique()
Copied!
1
@Entity()
2
class StringIdEntity(
3
int id;
4
5
@Index() // or alternatively use @Unique()
6
String uid;
7
)
8
9
10
final objects = box.query(StringIdEntity_.uid.equals('...')).build().find();
Copied!
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.
If you need to assign IDs by yourself have a look at how to switch to self-assigned IDs and what side effects apply.

Make entity data accessible

ObjectBox needs to access the data of your entity’s properties (e.g. in the generated code). You have two options:
    1.
    Make sure properties do not have private visibility.
    2.
    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.
Java
Kotlin
Dart
1
@Entity
2
public class User {
3
4
// Option 1: field is not private.
5
@Id long id;
6
7
// Option 2: field is private, but getter is available.
8
private String name;
9
10
public String getName() {
11
return this.name;
12
}
13
14
// Required for ObjectBox.
15
public User() {
16
}
17
18
// Optional: all-properties constructor for better performance.
19
public User(id, name) {
20
this.id = id;
21
this.name = name;
22
}
23
}
Copied!
1
// For Kotlin a data class with default values
2
// meets all above requirements.
3
@Entity
4
data class User(
5
@Id var id: Long = 0,
6
var name: String? = null
7
)
Copied!
1
@Entity()
2
class User {
3
int id;
4
5
String? _name;
6
7
String get name {...}
8
9
set name(String value) {...}
10
11
User(this.id);
12
}
Copied!

Basic annotations for entity properties

Transient

@Transient marks properties that should not be persisted. In Java static or transient properties will also not be persisted.
Java
Kotlin
Dart
1
@Transient
2
private int notPersisted;
Copied!
1
@Transient
2
var notPersisted: Int = 0
Copied!
1
@Transient()
2
int? notPersisted;
Copied!

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.
    We recommend using @Uid annotations to rename properties and even entities instead.
    @NameInDb only works with inline constants to specify a column name.
Java
Kotlin
1
@NameInDb("username")
2
private String name;
Copied!
1
@NameInDb("username")
2
var name: String? = null
Copied!

Property Indexes with @Index

Annotate a property with @Index to create a database index for the corresponding database column. This can improve performance when querying for that property.
Java
Kotlin
Dart
1
@Index
2
private String name;
Copied!
@Index is currently not supported for String[], byte[], float and double
1
@Index
2
var name: String? = null
Copied!
@Index is currently not supported for Array<String>, ByteArray , Float and Double
1
@Index()
2
String name;
Copied!
@Index is currently not supported for double and listsList<String>, List<int>, Uint8List, Int8List
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:
Java
Kotlin
Dart
1
@Index(type = IndexType.VALUE)
2
private String name;
Copied!
1
@Index(type = IndexType.VALUE)
2
var name: String? = null
Copied!
1
@Index(type: IndexType.value)
2
String name;
Copied!
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.

Unique constraints

Annotate a property with @Unique to enforce that values are unique before an entity is put:
Java
Kotlin
Dart
1
@Unique
2
private String name;
Copied!
1
@Unique
2
var name: String? = null
Copied!
1
@Unique()
2
String? name;
Copied!
A put() operation will abort and throw a UniqueViolationException if the unique constraint is violated:
Java
Kotlin
Dart
1
try {
2
box.put(new User("Sam Flynn"));
3
} catch (UniqueViolationException e) {
4
// A User with that name already exists.
5
}
Copied!
1
try {
2
box.put(User("Sam Flynn"))
3
} catch (e: UniqueViolationException) {
4
// A User with that name already exists.
5
}
Copied!
1
try {
2
box.put(User('Sam Flynn'))
3
} on UniqueViolationException catch (e) {
4
// A User with that name already exists.
5
}
Copied!
For a single property it is possible to specify that a conflicting object should be replaced instead of an exception being thrown:
Java
Kotlin
1
@Unique(onConflict = ConflictStrategy.REPLACE)
2
private String name;
Copied!
1
@Unique(onConflict = ConflictStrategy.REPLACE)
2
var name: String? = null
Copied!
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.
Java
Kotlin
Dart
1
// Store 64-bit integer as time in nanoseconds.
2
@Type(DatabaseType.DateNano)
3
private long timeInNanos;
Copied!
1
// Store 64-bit integer as time in nanoseconds.
2
@Type(DatabaseType.DateNano)
3
var timeInNanos: Long = 0
Copied!
1
// Time with nanosecond precision.
2
@Property(type: PropertyType.dateNano)
3
DateTime nanoDate;
4
5
@Property(type: PropertyType.byte)
6
int byte; // 1 byte
7
8
@Property(type: PropertyType.short)
9
int short; // 2 bytes
10
11
@Property(type: PropertyType.char)
12
int char; // 1 bytes
13
14
@Property(type: PropertyType.int)
15
int int32; // 4 bytes
16
17
@Property(type: PropertyType.float)
18
double float; // 4 bytes
19
20
@Property(type: PropertyType.byteVector)
21
List<int> byteList;
Copied!

Relations

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

Triggering code generation

Once your entity schema is in place, you can trigger the code generation process.
Last modified 8d ago