Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Datos del modelo

Relationships - Java SDK

Realm permite definir relaciones explícitas entre los tipos de objetos de una aplicación. Una relación es una propiedad de objeto que hace referencia a otro objeto de Realm, en lugar de a uno de los tipos de datos primitivos. Las relaciones se definen estableciendo el tipo de una propiedad de objeto a otro tipo de objeto en el... esquema de propiedad.

Relationships are direct references to other objects in a realm, which means that you don't need bridge tables or explicit joins to define a relationship like you would in a relational database. Instead you can access related objects by reading and writing to the property that defines the relationship. Realm executes read operations lazily as they come in, so querying a relationship is just as performant as reading a regular property.

Hay tres tipos principales de relaciones entre objetos:

Puede definir relaciones, colecciones y objetos incrustados en su esquema de objetos utilizando los siguientes tipos:

  • RealmObject

  • RealmList <? extends RealmObject>

Utilice anotaciones para indicar si un campo determinado representa una relación de clave externa o de objeto incrustado. Para obtener más información, consulte Anotaciones de relación.

A to-one relationship means that an object is related in a specific way to no more than one other object. You define a to-one relationship for an object type in its object schema by specifying a property where the type is the related Realm object type.

Setting a relationship field to null removes the connection between objects, but Realm does not delete the referenced object unless that object is embedded.

A to-many relationship means that an object is related in a specific way to multiple objects. You can create a relationship between one object and any number of objects using a field of type RealmList<T> where T is a Realm object in your application:

An inverse relationship links an object back to any other objects that refer to it in a defined to-one or to-many relationship. Relationship definitions are unidirectional, so you must explicitly define a property in the object's model as an inverse relationship.

Por ejemplo, la relación "El usuario tiene muchas tareas" no crea automáticamente la relación inversa "La tarea pertenece al usuario". Si no se especifica la relación inversa en el modelo de objetos, se deberá ejecutar una consulta independiente para buscar al usuario asignado a una tarea determinada.

Para definir una relación inversa, defina una propiedad LinkingObjects en su modelo de objetos. La definición LinkingObjects especifica el tipo de objeto y el nombre de la propiedad de la relación que invierte.

Realm automatically updates implicit relationships whenever an object is added or removed in the specified relationship. You cannot manually set the value of an inverse relationship property.

Fields annotated with @LinkingObjects must be:

  • marked final

  • de tipo RealmResults<T> donde T es el tipo en el extremo opuesto de la relación

Since relationships are many-to-one or many-to-many, following inverse relationships can result in zero, one, or many objects.

Like any other RealmResults set, you can query an inverse relationship.

Tip

Alternatively, you can define your relationships in your App Services app.

Advertencia

Always Define Accessors and Mutators for Modifiable Fields

Los objetos Realm utilizan getters y setters para persistir los valores de campo actualizados en sus realms. Utilice siempre getters y setters para las actualizaciones.

Para configurar una relación muchos a uno o uno a uno, crea un campo cuyo tipo sea un objeto Realm en tu aplicación:

import io.realm.RealmObject;
public class Frog extends RealmObject {
private String name;
private int age;
private String species;
private String owner;
private Frog bestFriend;
public Frog(String name, int age, String species, String owner, Frog bestFriend) {
this.name = name;
this.age = age;
this.species = species;
this.owner = owner;
this.bestFriend = bestFriend;
}
public Frog(){} // RealmObject subclasses must provide an empty constructor
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getSpecies() { return species; }
public void setSpecies(String species) { this.species = species; }
public String getOwner() { return owner; }
public void setOwner(String owner) { this.owner = owner; }
public Frog getBestFriend() { return bestFriend; }
public void setBestFriend(Frog bestFriend) { this.bestFriend = bestFriend; }
}
import io.realm.RealmObject
open class Frog : RealmObject {
var name: String? = null
var age = 0
var species: String? = null
var owner: String? = null
var bestFriend: Frog? = null
constructor(
name: String?,
age: Int,
species: String?,
owner: String?,
bestFriend: Frog?
) {
this.name = name
this.age = age
this.species = species
this.owner = owner
this.bestFriend = bestFriend
}
constructor() {} // RealmObject subclasses must provide an empty constructor
}

Importante

To-one relationships must be optional

When you declare a to-one relationship in your object model, it must be an optional property. If you try to make a to-one relationship required, Realm throws an exception at runtime.

Cada Frog hace referencia a cero Frog instancias o a una instancia Frog diferente. Nada impide que múltiples instancias Frog hagan referencia al mismo Frog como mejor amigo; la distinción entre una relación muchos-a-uno y uno-a-uno depende de su aplicación.

import io.realm.RealmList;
import io.realm.RealmObject;
public class Frog extends RealmObject {
private String name;
private int age;
private String species;
private String owner;
private RealmList<Frog> bestFriends;
public Frog(String name, int age, String species, String owner, RealmList<Frog> bestFriends) {
this.name = name;
this.age = age;
this.species = species;
this.owner = owner;
this.bestFriends = bestFriends;
}
public Frog(){} // RealmObject subclasses must provide an empty constructor
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getSpecies() { return species; }
public void setSpecies(String species) { this.species = species; }
public String getOwner() { return owner; }
public void setOwner(String owner) { this.owner = owner; }
public RealmList<Frog> getBestFriends() { return bestFriends; }
public void setBestFriends(RealmList<Frog> bestFriends) { this.bestFriends = bestFriends; }
}
import io.realm.RealmList
import io.realm.RealmObject
open class Frog : RealmObject {
var name: String? = null
var age = 0
var species: String? = null
var owner: String? = null
var bestFriends: RealmList<Frog>? = null
constructor(
name: String?,
age: Int,
species: String?,
owner: String?,
bestFriends: RealmList<Frog>?
) {
this.name = name
this.age = age
this.species = species
this.owner = owner
this.bestFriends = bestFriends
}
constructor() {} // RealmObject subclasses must provide an empty constructor
}

RealmList s are containers of RealmObject s, but otherwise behave like a regular collection. You can use the same object in multiple RealmList s.

Por defecto, las relaciones de Realm son unidireccionales. Puede seguir un enlace desde una clase a una clase referenciada, pero no en la dirección opuesta. Considera la siguiente clase que define un Toad con una lista de frogFriends:

import io.realm.RealmList;
import io.realm.RealmObject;
public class Toad extends RealmObject {
private RealmList<Frog> frogFriends;
public Toad(RealmList<Frog> frogFriends) {
this.frogFriends = frogFriends;
}
public Toad() {}
public RealmList<Frog> getFrogFriends() { return frogFriends; }
public void setFrogFriends(RealmList<Frog> frogFriends) { this.frogFriends = frogFriends; }
}
import io.realm.RealmList
import io.realm.RealmObject
open class Toad : RealmObject {
var frogFriends: RealmList<Frog>? = null
constructor(frogFriends: RealmList<Frog>?) {
this.frogFriends = frogFriends
}
constructor() {}
}

Puedes proporcionar un enlace en la dirección opuesta, desde Frog hasta Toad, con la anotación @LinkingObjects en un campo final (en Java) o val (en Kotlin) de tipo RealmResults<T>:

import io.realm.RealmObject;
import io.realm.RealmResults;
import io.realm.annotations.LinkingObjects;
public class Frog extends RealmObject {
private String name;
private int age;
private String species;
private String owner;
@LinkingObjects("frogFriends")
private final RealmResults<Toad> toadFriends = null;
public Frog(String name, int age, String species, String owner) {
this.name = name;
this.age = age;
this.species = species;
this.owner = owner;
}
public Frog(){} // RealmObject subclasses must provide an empty constructor
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getSpecies() { return species; }
public void setSpecies(String species) { this.species = species; }
public String getOwner() { return owner; }
public void setOwner(String owner) { this.owner = owner; }
}
import io.realm.RealmObject
import io.realm.RealmResults
import io.realm.annotations.LinkingObjects
open class Frog : RealmObject {
var name: String? = null
var age = 0
var species: String? = null
var owner: String? = null
@LinkingObjects("frogFriends")
private val toadFriends: RealmResults<Toad>? = null
constructor(name: String?, age: Int, species: String?, owner: String?) {
this.name = name
this.age = age
this.species = species
this.owner = owner
}
constructor() {} // RealmObject subclasses must provide an empty constructor
}

Importante

Los campos de relación inversa deben marcarse final.

Volver

Define un modelo de objeto

En esta página