Realm Models

suggest change

Realm models must extend the RealmObject base class, they define the schema of the underlying database.

Supported field types are boolean, byte, short, int, long, float, double, String, Date, byte[], links to other RealmObjects, and RealmList<T extends RealmModel>.

public class Person extends RealmObject {
    @PrimaryKey //primary key is also implicitly an @Index 
                //it is required for `copyToRealmOrUpdate()` to update the object.
    private long id;

    @Index //index makes queries faster on this field
    @Required //prevents `null` value from being inserted
    private String name; 

    private RealmList<Dog> dogs; //->many relationship to Dog

    private Person spouse; //->one relationship to Person

    private Calendar birthday; //calendars are not supported but can be ignored

    // getters, setters

If you add (or remove) a new field to your RealmObject (or you add a new RealmObject class or delete an existing one), a migration will be needed. You can either set deleteIfMigrationNeeded() in your RealmConfiguration.Builder, or define the necessary migration. Migration is also required when adding (or removing) @Required, or @Index, or @PrimaryKey annotation.

Relationships must be set manually, they are NOT automatic based on primary keys.

Since 0.88.0, it is also possible to use public fields instead of private fields/getters/setters in RealmObject classes.

It is also possible to implement RealmModel instead of extending RealmObject, if the class is also annotated with @RealmClass.

public class Person implements RealmModel {
    // ...

In that case, methods like person.deleteFromRealm() or person.addChangeListener() are replaced with RealmObject.deleteFromRealm(person) and RealmObject.addChangeListener(person).

Limitations are that by a RealmObject, only RealmObject can be extended, and there is no support for final, volatile and transient fields.

It is important that a managed RealmObject class can only be modified in a transaction. A managed RealmObject cannot be passed between threads.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents