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

Anotaciones de la propiedad - Kotlin SDK

En esta página se describen las anotaciones disponibles que puedes usar para personalizar el comportamiento de las propiedades en tus modelos de objetos. Para obtener más información sobre cómo definir tu modelo de objetos, consulta Definir un Modelo de objeto Realm - Kotlin SDK.

El SDK de Kotlin proporciona varias anotaciones de propiedades que añaden funcionalidad a las propiedades de los objetos Realm. Consulte también Referencia de API de anotaciones.

Nota

Property Declarations

En Kotlin, los tipos de valor son implícitamente no nulos. Puedes declarar propiedades opcionales (nulos) usando la función integrada ? Operador de Kotlin. También puede asignar un valor predeterminado a una propiedad en su declaración. Consulte la lista de tipos de datos admitidos para ver ejemplos.

Los ejemplos de esta página hacen referencia a la siguiente clase Frog:

class Frog : RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId() // Primary key property
@Index
var name: String = "" // Indexed property
@Ignore
var age: Int = 0 // Ignored property
@PersistedName("latin_name")
var species: String? = null // Remapped property
@FullText
var physicalDescription: String? = null // Full-text search indexed property
}

A primary key is a unique identifier for an object in a realm. No other object of the same type can share an object's primary key.

To specify a property as the object type's primary key, use the @PrimaryKey annotation:

@PrimaryKey
var _id: ObjectId = ObjectId() // Primary key property

Aspectos importantes de las claves primarias:

  • Puede definir solo una clave principal por esquema de objeto.

  • No puedes cambiar el campo llave primaria para un tipo de objeto Realm después de agregar cualquier objeto de ese tipo a un realm.

  • Los valores de clave primaria deben ser únicos en todas las instancias de un objeto en un realm. Intentar insertar un valor duplicado de llave primaria produce un error.

  • Los valores de la llave primaria son inmutables. Para cambiar el valor de la clave primaria de un objeto, se debe borrar el objeto original e insertar uno nuevo con un valor de clave primaria diferente.

  • Primary keys are nullable. Because primary key values must be unique, null can only be the primary key of one object in a collection.

  • Realm automatically indexes primary keys, so you can efficiently read and modify objects based on their primary key.

You can create a primary key with any of the following types:

  • String

  • Byte

  • Char

  • Short

  • Int

  • Long

  • ObjectId

  • RealmUUID

Importante

Device Sync requiere un campo llave primaria _id.

If you use Device Sync, your object models must include a primary key field named _id, which must be be of type String, Int, or ObjectId.

For more information, refer to Model Data with Device Sync - Kotlin SDK.

New in version 10.8.0: Remap class names with @PersistedName

By default, Realm uses the name defined in the model class to represent classes and fields internally. The Kotlin SDK lets you map a property or class name to a different persisted name than the name used in your code. Persisting a different name to the realm is useful in some cases, including:

  • Para facilitar el trabajo entre plataformas donde las convenciones de nomenclatura difieren. Por ejemplo, si los nombres de las propiedades del esquema de Device Sync usan snake case, mientras que tu proyecto usa camel case.

  • To change a class or field name in Kotlin without forcing a migration.

  • To support multiple model classes with the same simple name in different packages.

  • To use a class name that is longer than the 57-character limit enforced by Realm.

To map a Kotlin class or property name in your code to a different name to persist in a realm:

  1. Utiliza la anotación @PersistedName en la clase o propiedad de Kotlin.

  2. Specify a class or property name that you want persisted to the realm.

En este ejemplo, Frog es el nombre de la clase Kotlin utilizada en el código en todo el proyecto para realizar operaciones CRUD, y Frog_Entity es el nombre persistente usado para almacenar objetos en un realm:

@PersistedName(name = "Frog_Entity") // Remapped class name
class Frog : RealmObject {
@PrimaryKey
var _id: ObjectId = ObjectId()
var name: String = ""
var age: Int = 0
var species: String? = null
var owner: String? = null
}

Importante

Consultas por nombres de clases reasignados

When querying an inverse relationship on an object with a remapped class name, you must use the persisted class name. In the example above, you must query Frog_Entity instead of Frog. For more information, refer to Query Inverse Relationships.

In this example, species is the Kotlin property name used in the code throughout the project to perform CRUD operations and latin_name is the persisted name used to store values in a realm:

@PersistedName("latin_name")
var species: String? = null // Remapped property

Tip

Querying by Remapped Property Names

You can query by both the Kotlin name used in the code and by the persisted name stored in a realm. For more information, refer to :ref:``

Si escribes en un realm sincronizado, el esquema sincronizar ve los valores almacenados utilizando el nombre persistente de clase o propiedad. Tenga en cuenta lo siguiente:

  • Migrations must use the persisted class or property name.

  • Cualquier error de esquema reportado utiliza el nombre almacenado.

By default, Realm manages properties defined in your Realm object model. However, you can choose to ignore properties that you don't want to persist in a realm.

To ignore a property and prevent it from persisting in a realm, use the @Ignore annotation:

@Ignore
var age: Int = 0 // Ignored property

An ignored property behaves exactly like a managed property, except they aren't stored to the database, can't be used in queries, and don't trigger Realm notifications. You can mix managed and ignored properties within a class.

Indexes are special data structures that store a small portion of a realm's data in an easy-to-traverse form. Indexes support more efficient query execution in a realm. When an appropriate index exists for a query, Realm uses the index to limit the number of documents that it must inspect. Otherwise, Realm must scan every document in a collection and select those documents that match a query.

The index stores the value of a specific field ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. While indexes speed up some queries, they also cause slightly slower writes. They come with additional storage and memory overhead. Realm stores indexes on disk, which makes your realm files larger. Each index entry is a minimum of 12 bytes.

Para crear un índice en una propiedad, utilice la anotación @Index en la propiedad:

@Index
var name: String = "" // Indexed property

Nota

Las llaves primarias están indexadas por defecto.

You can index fields with the following types:

  • String

  • Byte

  • Short

  • Int

  • Long

  • Boolean

  • RealmInstant

  • ObjectId

  • RealmUUID

You cannot combine standard indexes with full-text search (FTS) indexes on the same property. To create an FTS index on a property, refer to the Full-Text Search Indexes section.

Además de los índices estándar, Realm también admite índices de texto completo (FTS) en String propiedades. Aunque es posible query un campo de string con o sin un índice estándar, un índice FTS permite buscar varias palabras y frases y excluir otras.

Para crear un índice FTS en una propiedad, utilice la anotación @FullText:

@FullText
var physicalDescription: String? = null // Full-text search indexed property

Toma en cuenta las siguientes restricciones sobre los índices de texto completo:

  • You can only create an FTS index on properties of String type.

  • No puede combinar índices de texto completo y índices estándar en la misma propiedad. Para crear un índice estándar en una propiedad, consultar la sección Propiedades del Índice.

Nota

Character Limitations for Full-Text Search Indexes

For Full-Text Search (FTS) indexes, only ASCII and Latin-1 alphanumerical chars (most western languages) are included in the index.

Indexes are diacritics- and case-insensitive.

For more information on querying full-text indexes, refer to Filter By Full-Text Search (FTS) Property.

Volver

Tipos de datos admitidos

En esta página