This page describes Realm object types and how to define Realm objects as part of your application's data model. After you define your object model, you can open a realm with a schema that includes your defined objects and work with them in the realm.
The Kotlin SDK memory maps Realm objects directly to native Kotlin objects, so there's no need to use a special data access library. You define your application's data model via regular Kotlin classes declared in your application code object.
Para obtener información sobre cómo realizar cambios en sus objetos Realm después de definir su modelo de objetos Realm, consulte Cambiar un modelo de objeto.
Nota
Define Data Model with Device Sync
If your app uses Atlas Device Sync, there are additional considerations when defining your data model. For more information, refer to Model Data with Device Sync - Kotlin SDK.
Objetos del reino
Realm objects are uniquely named instances of Kotlin classes that you can work with as you would any other class instance.
Cada clase de objeto representa un tipo de objeto. Los objetos del mismo tipo comparten un esquema de objeto, que define sus propiedades y relaciones. El SDK garantiza que todos los objetos de un dominio se ajusten al esquema de su tipo y valida los objetos al crearlos, modificarlos o eliminarlos.
Sin embargo, ten en cuenta que los objetos Realm tienen las siguientes restricciones:
Los objetos del reino deben heredar del
RealmObjectClase o sus subclases:EmbeddedRealmObjectAsymmetricRealmObjecto. El SDK de Kotlin no admite la herencia de clases base personalizadas.El SDK de Kotlin requiere que los objetos Realm tengan un constructor vacío. Consulte El ejemplo de solución alternativa se detalla en la siguiente sección.
Class names are limited to a maximum of 57 UTF-8 characters.
Además, el SDK de Kotlin no admite el uso de clases de datos deKotlin. Para modelar datos. Esto se debe a que las clases de datos se suelen usar para datos inmutables, lo cual contradice la forma en que el SDK de Kotlin de Realm modela los datos.
Define a New Object Type
Para definir un nuevo tipo de objeto Realm, debes crear una clase Kotlin con un nombre único que implementar la interfaz RealmObject, EmbeddedRealmObject o AsymmetricRealmObject.
Nota
Class names are limited to a maximum of 57 UTF-8 characters.
Then, you specify your object's properties, including:
El tipo de dato para cada propiedad. El Kotlin SDK admite los siguientes tipos de datos:
a limited subset of BSON types
Realm-specific types, which you can use for unique identifiers, timestamps, counters, and collections
Cualquier anotación de propiedad que añada funcionalidad a las propiedades de los objetos de Realm. Puedes usar anotaciones para:
Designate a property as a primary key
Mark a property as indexable
Ignore a property
Map a property or class name to another name
Cualquier relación con otros objetos de Realm.
After you've defined your Realm object model, you can pass the set of object classes to the realm's configuration when you open a realm, and then work with those objects in the realm.
Importante
Realm Requires an Empty Constructor
El Realm Kotlin SDK no admite tener un solo constructor primario. El SDK requiere un constructor vacío para crear objetos. Como solución alternativa, puedes hacer algo similar a lo siguiente:
class Person(var name: String, var age: Int): RealmObject { constructor(): this("", 0) // Empty constructor required by Realm }
Definir un tipo de objeto de reino
To define a Realm object type, create a Kotlin class that implements the RealmObject interface:
// Implements the `RealmObject` interface class Frog : RealmObject { // Empty constructor required by Realm var _id: ObjectId = ObjectId() var name: String = "" var age: Int = 0 var species: String? = null var owner: String? = null }
You can then use the object as a property to define relationships with other Realm objects.
Define an Embedded Object Type
Un EmbeddedRealmObject es un tipo especial de objeto Realm que modela datos complejos sobre un objeto específico. Realm trata cada objeto incrustado como datos anidados dentro de un único objeto principal específico.
Because of this, embedded objects have the following constraints:
Un objeto incrustado requiere un objeto padre y no puede existir como un objeto Realm independiente. Si el objeto padre deja de referenciar el objeto incrustado, el objeto incrustado se elimina automáticamente.
Un objeto incrustado hereda el ciclo de vida de su objeto principal. Por ejemplo, si se borra el objeto padre, el objeto incrustado se borra también.
Embedded objects have strict ownership with their parent object. You cannot reassign an embedded object to a different parent object, or share an embedded object between multiple parent objects.
Los objetos incrustados no pueden tener una llave primaria.
Tip
Si necesitas gestionar manualmente el ciclo de vida de un objeto referenciado o quieres que los objetos referenciados persistan tras la eliminación del objeto principal, utiliza un objeto Realm normal con una relación. Para obtener más información, consulte Relaciones - Kotlin SDK.
Para definir un tipo de objeto incrustado, cree una clase Kotlin que implemente la interfaz EmbeddedRealmObject:
// Implements `EmbeddedRealmObject` interface class EmbeddedAddress : EmbeddedRealmObject { // CANNOT have primary key var street: String? = null var city: String? = null var state: String? = null var postalCode: String? = null var propertyOwner: Contact? = null }
Los tipos de objetos incrustados son reutilizables y componibles. Puedes usar el mismo tipo de objeto incrustado en varios tipos de objetos principales dentro de otros tipos de objetos incrustados.
After you define your embedded object type, you must define a relationship with a parent object in your data model. To learn how, refer to Define an Embedded Object.
Define an Asymmetric Object Type
Novedades en la versión 1.10.0.
An AsymmetricRealmObject is an insert-only object intended to be used with the Atlas Device Sync feature Data Ingest. For information on how to set up Data Ingest with your application, refer to Stream Data to Atlas - Kotlin SDK.
Los objetos asimétricos admiten ampliamente los mismos tipos de propiedades que RealmObject, con algunas excepciones:
Asymmetric objects can only be used in synced realms configured with Flexible Sync. However, you cannot create subscriptions to asymmetric objects.
Un
AsymmetricRealmObjectpuede contenerEmbeddedRealmObjecttipos, pero no puede contenerRealmObjecttipos ni otros tipos deAsymmetricRealmObject.AsymmetricRealmObjecttypes cannot be used as properties in other Realm objects.
Additionally, asymmetric objects do not function in the same way as other Realm objects. You cannot add, read, update, or delete an asymmetric object from the realm. You can only create an asymmetric object, which then syncs unidirectionally to the Atlas database linked to your App with Device Sync. Realm then deletes this object after syncing.
Para definir un tipo de objeto asimétrico, cree una clase Kotlin que implemente la interfaz AsymmetricRealmObject:
// Implements the `AsymmetricRealmObject` interface class WeatherSensor : AsymmetricRealmObject { var id: ObjectId = ObjectId() var deviceId: String = "" var temperatureInFarenheit: Float = 0.0F var barometricPressureInHg: Float = 0.0F var windSpeedInMph: Int = 0 }
En las versiones del SDK de Kotlin 1.11.1 y anteriores, no se puede enlazar tipos de AsymmetricRealmObject a tipos de RealmObject. En versiones del SDK 1.12.0 y posteriores, los tipos AsymmetricRealmObject pueden vincularse a tipos RealmObject además de los tipos EmbeddedRealmObject.
Define Collection Properties
A collection is an object that contains zero or more instances of a supported data type. Realm collections are homogenous (all objects in a collection are of the same type) and are backed by their corresponding built-in Kotlin classes. For more information on the collection types used in the Kotlin SDK and their supported data types, refer to Collection Types.
The Kotlin SDK offers several collection types that you can use as properties in your data model: RealmList, RealmSet, and RealmDictionary.
Las colecciones también te permiten definir relaciones tipo to-many entre los objetos de Realm. Consulta Relaciones - Kotlin SDK para obtener más información.
Importante
Initialize Collection Properties
Los tipos de colección no son nulos. Al definir una propiedad de colección,debe inicializarla.
Definir una RealmList
To define a property as a RealmList, specify its type within the object schema as RealmList<E> and initialize the default value using realmListOf():
// RealmList<E> can be any supported primitive // or BSON type, a RealmObject, or an EmbeddedRealmObject class Frog : RealmObject { var _id: ObjectId = ObjectId() var name: String = "" // List of RealmObject type (CANNOT be nullable) var favoritePonds: RealmList<Pond> = realmListOf() // List of EmbeddedRealmObject type (CANNOT be nullable) var favoriteForests: RealmList<EmbeddedForest> = realmListOf() // List of primitive type (can be nullable) var favoriteWeather: RealmList<String?> = realmListOf() } class Pond : RealmObject { var _id: ObjectId = ObjectId() var name: String = "" }
Defina un RealmSet
Para definir una propiedad como un RealmSet, especifica su tipo en el esquema de objeto como RealmSet<E> e inicializa el valor predeterminado usando realmSetOf():
// RealmSet<E> can be any supported primitive or // BSON type or a RealmObject class Frog : RealmObject { var _id: ObjectId = ObjectId() var name: String = "" // Set of RealmObject type (CANNOT be nullable) var favoriteSnacks: RealmSet<Snack> = realmSetOf() // Set of primitive type (can be nullable) var favoriteWeather: RealmSet<String?> = realmSetOf() } class Snack : RealmObject { var _id: ObjectId = ObjectId() var name: String = "" }
Definir un RealmDictionary/RealmMap
Para definir una propiedad como RealmDictionary, especifica su tipo dentro del esquema del objeto como RealmDictionary<K, V> e inicializa el valor predeterminado utilizando realmDictionaryOf():
// RealmDictionary<K, V> can be any supported // primitive or BSON types, a RealmObject, or // an EmbeddedRealmObject class Frog : RealmObject { var _id: ObjectId = ObjectId() var name: String = "" // Dictionary of RealmObject type (value MUST be nullable) var favoriteFriendsByPond: RealmDictionary<Frog?> = realmDictionaryOf() // Dictionary of EmbeddedRealmObject type (value MUST be nullable) var favoriteTreesInForest: RealmDictionary<EmbeddedForest?> = realmDictionaryOf() // Dictionary of primitive type (value can be nullable) var favoritePondsByForest: RealmDictionary<String?> = realmDictionaryOf() }
Realm disallows the use of . or $ characters in map keys. You can use percent encoding and decoding to store a map key that contains one of these disallowed characters.
// Percent encode . or $ characters to use them in map keys val mapKey = "Hundred Acre Wood.Northeast" val encodedMapKey = "Hundred Acre Wood%2ENortheast"
Define Unstructured Data
Nuevo en la versión 2.0.0.
A partir de la versión 2.0.0 de Kotlin SDK, puedes almacenar colecciones de datos mixtos dentro de una propiedad RealmAny. Puedes utilizar esta funcionalidad para modelar estructuras de datos complejas, como documentos JSON o MongoDB, sin tener que definir un modelo de datos estricto.
Unstructured data is data that doesn't easily conform to an expected schema, making it difficult or impractical to model to individual data classes. For example, your app might have highly variable data or dynamic data whose structure is unknown at runtime.
Storing collections in a mixed property offers flexibility without sacrificing functionality, including performant synchronization when using Device Sync. And you can work with them the same way you would a non-mixed collection:
Se pueden anidar colecciones mixtas hasta 100 niveles.
You can query on and react to changes on mixed collections.
You can find and update individual mixed collection elements.
However, storing data in mixed collections is less performant than using a structured schema or serializing JSON blobs into a single string property.
Para modelar datos no estructurados en tu aplicación, define las propiedades adecuadas en tu esquema como tipos RealmAny. Puedes configurar estas RealmAny propiedades como una colección RealmList o RealmDictionary de RealmAny elementos. Ten en cuenta que RealmAny no puede representar un RealmSet ni un objeto incrustado.
Tip
Use a map of mixed data types when the type is unknown but each value will have a unique identifier.
Utilice una lista de tipos de datos mixtos cuando el tipo sea desconocido, pero el orden de los objetos sea importante.