Docs Menu
Docs Home
/ /
CRUD

CRUD - Update - Java SDK

Los ejemplos de esta página utilizan el modelo de datos de una aplicación de gestión de proyectos que tiene dos tipos de objetos Realm: Project y Task. Un Project tiene cero o más Tasks.

Vea el esquema de estas dos clases, Project y Task, a continuación:

ProjectTask.java
import org.bson.types.ObjectId;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.RealmClass;
import io.realm.annotations.Required;
public class ProjectTask extends RealmObject {
@PrimaryKey
public ObjectId _id;
@Required
public String name;
public String assignee;
public int progressMinutes;
public boolean isComplete;
public int priority;
@Required
public String _partition;
}
Project.java
import org.bson.types.ObjectId;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.RealmClass;
import io.realm.annotations.Required;
public class Project extends RealmObject {
@PrimaryKey
public ObjectId _id;
@Required
public String name;
public RealmList<ProjectTask> tasks = new RealmList<>();
}
ProjectTask.kt
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required
import org.bson.types.ObjectId
open class ProjectTask(
@PrimaryKey
var _id: ObjectId = ObjectId(),
@Required
var name: String = "",
var assignee: String? = null,
var progressMinutes: Int = 0,
var isComplete: Boolean = false,
var priority: Int = 0,
var _partition: String = ""
): RealmObject()
Proyecto.kt
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required
import org.bson.types.ObjectId
open class Project(
@PrimaryKey
var _id: ObjectId = ObjectId(),
@Required
var name: String = "",
var tasks: RealmList<ProjectTask> = RealmList(),
): RealmObject()

Dentro de una transacción, puedes actualizar un objeto Realm de la misma forma que cualquier otro objeto en el idioma que elijas. Simplemente asigna un nuevo valor a la propiedad o actualízala.

El siguiente ejemplo cambia el nombre de la tortuga a "Archibald" y establece la edad de Archibald en 101 asignando nuevos valores a las propiedades:

realm.executeTransaction(r -> {
// Get a turtle to update.
Turtle turtle = r.where(Turtle.class).findFirst();
// Update properties on the instance.
// This change is saved to the realm.
turtle.setName("Archibald");
turtle.setAge(101);
});
realm.executeTransaction { r: Realm ->
// Get a turtle to update.
val turtle = r.where(Turtle::class.java).findFirst()
// Update properties on the instance.
// This change is saved to the realm.
turtle!!.name = "Archibald"
turtle.age = 101
}

Una operación de upsert es una operación de escritura que inserta un nuevo objeto con una clave primaria dada o actualiza un objeto existente que ya la tiene. Se denomina upsert porque es una operación de "actualización o inserción". Esto es útil cuando un objeto puede o no existir, como al importar un conjunto de datos en masa a un dominio existente. Upsert es una forma elegante de actualizar entradas existentes al añadir nuevas.

El siguiente ejemplo muestra cómo insertar un objeto con realm. Creamos un nuevo entusiasta de las tortugas llamado "Drew" y luego actualizamos su nombre a "Andy" usando insertarOActualizar():

realm.executeTransaction(r -> {
ObjectId id = new ObjectId();
TurtleEnthusiast drew = new TurtleEnthusiast();
drew.set_id(id);
drew.setName("Drew");
drew.setAge(25);
// Add a new turtle enthusiast to the realm. Since nobody with this id
// has been added yet, this adds the instance to the realm.
r.insertOrUpdate(drew);
TurtleEnthusiast andy = new TurtleEnthusiast();
andy.set_id(id);
andy.setName("Andy");
andy.setAge(56);
// Judging by the ID, it's the same turtle enthusiast, just with a different name.
// As a result, you overwrite the original entry, renaming "Drew" to "Andy".
r.insertOrUpdate(andy);
});
realm.executeTransaction { r: Realm ->
val id = ObjectId()
val drew = TurtleEnthusiast()
drew._id = id
drew.name = "Drew"
drew.age = 25
// Add a new turtle enthusiast to the realm. Since nobody with this id
// has been added yet, this adds the instance to the realm.
r.insertOrUpdate(drew)
val andy = TurtleEnthusiast()
andy._id = id
andy.name = "Andy"
andy.age = 56
// Judging by the ID, it's the same turtle enthusiast, just with a different name.
// As a result, you overwrite the original entry, renaming "Drew" to "Andy".
r.insertOrUpdate(andy)
}

También puede usar copyToRealmOrUpdate() para crear un nuevo objeto basado en un objeto proporcionado o actualizar un objeto existente con el mismo valor de clave principal. Use el indicador de CHECK_SAME_VALUES_BEFORE_SET importación para actualizar únicamente los campos que sean diferentes en el objeto proporcionado:

El siguiente ejemplo demuestra cómo insertar un objeto o, si ya existe un objeto con la misma clave principal, actualizar solo aquellos campos que difieren:

realm.executeTransaction(r -> {
ObjectId id = new ObjectId();
TurtleEnthusiast drew = new TurtleEnthusiast();
drew.set_id(id);
drew.setName("Drew");
drew.setAge(25);
// Add a new turtle enthusiast to the realm. Since nobody with this id
// has been added yet, this adds the instance to the realm.
r.insertOrUpdate(drew);
TurtleEnthusiast andy = new TurtleEnthusiast();
andy.set_id(id);
andy.setName("Andy");
// Judging by the ID, it's the same turtle enthusiast, just with a different name.
// As a result, you overwrite the original entry, renaming "Drew" to "Andy".
// the flag passed ensures that we only write the updated name field to the db
r.copyToRealmOrUpdate(andy, ImportFlag.CHECK_SAME_VALUES_BEFORE_SET);
});
realm.executeTransaction { r: Realm ->
val id = ObjectId()
val drew = TurtleEnthusiast()
drew._id = id
drew.name = "Drew"
drew.age = 25
// Add a new turtle enthusiast to the realm. Since nobody with this id
// has been added yet, this adds the instance to the realm.
r.insertOrUpdate(drew)
val andy = TurtleEnthusiast()
andy._id = id
andy.name = "Andy"
// Judging by the ID, it's the same turtle enthusiast, just with a different name.
// As a result, you overwrite the original entry, renaming "Drew" to "Andy".
r.copyToRealmOrUpdate(andy,
ImportFlag.CHECK_SAME_VALUES_BEFORE_SET)
}

Realm admite actualizaciones de toda la colección. Una actualización de colección aplica la misma actualización a propiedades específicas de varios objetos de la colección a la vez.

El siguiente ejemplo muestra cómo actualizar una colección. Gracias a la relación inversa implícita entre la owner propiedad de la tortuga y la turtles propiedad de TurtleEnthusiast, Realm actualiza automáticamente la lista de tortugas de Josephine al usar setObject() para actualizar la propiedad "owner" de todas las tortugas de la colección.

realm.executeTransaction(r -> {
// Create a turtle enthusiast named Josephine.
TurtleEnthusiast josephine = r.createObject(TurtleEnthusiast.class, new ObjectId());
josephine.setName("Josephine");
// Get all turtles named "Pierogi".
RealmResults<Turtle> turtles = r.where(Turtle.class).equalTo("name", "Pierogi").findAll();
// Give all turtles named "Pierogi" to Josephine
turtles.setObject("owner", josephine);
});
realm.executeTransaction { r: Realm ->
// Create a turtle enthusiast named Josephine.
val josephine = realm.createObject(
TurtleEnthusiast::class.java,
ObjectId()
)
josephine.name = "Josephine"
// Get all turtles named "Pierogi".
val turtles = r.where(Turtle::class.java)
.equalTo("name", "Pierogi")
.findAll()
// Give all turtles named "Pierogi" to Josephine
turtles.setObject("owner", josephine)
}

Como las colecciones realm siempre reflejan el último estado, pueden aparecer, desaparecer o cambiar mientras se recorre una colección. Para obtener una colección estable sobre la que se pueda iterar, se puede crear una snapshot de los datos de una colección. Un snapshot garantiza que el orden de los elementos no cambie, incluso si se elimina o modifica algún elemento.

Iterator Los objetos creados a partir de RealmResults usan instantáneas automáticamente. Iterator Los objetos creados a partir de RealmList instancias no usan instantáneas. Use RealmList.createSnapshot() o RealmResults.createSnapshot() para generar manualmente una instantánea que pueda iterar manualmente:

El siguiente ejemplo demuestra cómo iterar sobre una colección de forma segura utilizando una instantánea implícita creada a partir de un RealmResults Iterator o una instantánea manual creada a partir de un RealmList:

RealmResults<Frog> frogs = realm.where(Frog.class)
.equalTo("species", "bullfrog")
.findAll();
// Use an iterator to rename the species of all bullfrogs
realm.executeTransaction(r -> {
for (Frog frog : frogs) {
frog.setSpecies("Lithobates catesbeiana");
}
});
// Use a snapshot to rename the species of all bullfrogs
realm.executeTransaction(r -> {
OrderedRealmCollectionSnapshot<Frog> frogsSnapshot = frogs.createSnapshot();
for (int i = 0; i < frogsSnapshot.size(); i++) {
frogsSnapshot.get(i).setSpecies("Lithobates catesbeiana");
}
});
val frogs = realm.where(Frog::class.java)
.equalTo("species", "bullfrog")
.findAll()
// Use an iterator to rename the species of all bullfrogs
realm.executeTransaction {
for (frog in frogs) {
frog.species = "Lithobates catesbeiana"
}
}
// Use a snapshot to rename the species of all bullfrogs
realm.executeTransaction {
val frogsSnapshot = frogs.createSnapshot()
for (i in frogsSnapshot.indices) {
frogsSnapshot[i]!!.species = "Lithobates catesbeiana"
}
}

Volver

Lea

En esta página