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
/ /
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.

See the schema for these two classes, Project and Task, below:

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()
Project.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()

Within a transaction, you can update a Realm object the same way you would update any other object in your language of choice. Just assign a new value to the property or update the property.

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
}

An upsert is a write operation that either inserts a new object with a given primary key or updates an existing object that already has that primary key. We call this an upsert because it is an "update or insert" operation. This is useful when an object may or may not already exist, such as when bulk importing a dataset into an existing realm. Upserting is an elegant way to update existing entries while adding any new entries.

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:

The following example demonstrates how to insert an object or, if an object already exists with the same primary key, update only those fields that differ:

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 supports collection-wide updates. A collection update applies the same update to specific properties of several objects in a collection at once.

El siguiente ejemplo demuestra cómo actualizar una colección. Gracias a la relación inversa implícita entre la propiedad owner de Turtle y la propiedad turtles de TurtleEnthusiast, Realm actualiza automáticamente la lista de tortugas de Josephine cuando se usa setObject() para actualizar la propiedad "propietario" 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 de forma segura sobre una colección utilizando un snapshot implícito creado a partir de un RealmResults Iterator o un snapshot manual creado 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