Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Es posible que, en ocasiones, debas buscar un conjunto de tres o más tablas relacionadas entre sí. En ese caso, definirías relaciones anidadas entre las tablas.
Supongamos que, en el ejemplo de la app de transmisión de música, quieres consultar todos los usuarios, todas las playlists de cada uno de ellos y todas las canciones de cada playlist de cada usuario. Los usuarios tienen una relación uno a varios con las playlists, y estas tienen una relación varios a varios con las canciones. En el siguiente ejemplo de código, se muestran las clases que representan las entidades, así como la tabla de referencias cruzadas de la relación de varios a varios entre las playlists y las canciones:
Primero, modela la relación entre dos de las tablas del conjunto como lo harías normalmente, con una clase de datos y la anotación @Relation. En el siguiente ejemplo, se muestra una clase PlaylistWithSongs que modela una relación de varios a varios entre las clases de entidad Playlist y Song:
Después de definir una clase de datos que represente esa relación, crea otra clase de datos que modele la relación entre otra tabla del conjunto y la primera clase de relación, y "anida" la relación existente dentro de la nueva. En el siguiente ejemplo, se muestra una clase UserWithPlaylistsAndSongs que modela una relación de uno a varios entre la clase de entidad User y la clase de relación PlaylistWithSongs:
La clase UserWithPlaylistsAndSongs modela indirectamente las relaciones entre las tres clases de entidad User, Playlist y Song. Esto se ilustra en la figura 1.
Figura 1: Diagrama de clases de relaciones en el ejemplo de la app de transmisión de música.
Si hay más tablas en el conjunto, crea una clase para modelar la relación entre cada tabla restante y la clase de relación que modela las relaciones entre todas las tablas anteriores. Esto crea una cadena de relaciones anidadas entre todas las tablas que quieres consultar.
Por último, agrega un método a la clase DAO para exponer la función de consulta que necesita la app. El método requiere que Room ejecute varias búsquedas, así que agrega la anotación @Transaction para asegurarte de que toda la operación se realice automáticamente:
Kotlin
@Transaction@Query("SELECT * FROM User")fungetUsersWithPlaylistsAndSongs():List<UserWithPlaylistsAndSongs>
Java
@Transaction@Query("SELECT * FROM User")publicList<UserWithPlaylistsAndSongs>getUsersWithPlaylistsAndSongs();
El contenido y las muestras de código que aparecen en esta página están sujetas a las licencias que se describen en la Licencia de Contenido. Java y OpenJDK son marcas registradas de Oracle o sus afiliados.
Última actualización: 2025-07-27 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-07-27 (UTC)"],[],[],null,["# Define and query nested relationships\n\nSometimes, you might need to query a set of three or more tables that are all\nrelated to each other. In that case, you define *nested relationships* between\nthe tables.\n| **Caution:** Querying data with nested relationships requires Room to manipulate a large volume of data and can affect performance. Use as few nested relationships as possible in your queries.\n\nSuppose that in the music streaming app example, you want to query all the\nusers, all the playlists for each user, and all the songs in each playlist for\neach user. Users have a [one-to-many relationship](/training/data-storage/room/relationships/one-to-many) with playlists, and\nplaylists have a [many-to-many relationship](/training/data-storage/room/relationships/many-to-many) with songs. The following code\nexample shows the classes that represent these entities as well as the\ncross-reference table for the many-to-many relationship between playlists and\nsongs: \n\n### Kotlin\n\n @Entity\n data class User(\n @PrimaryKey val userId: Long,\n val name: String,\n val age: Int\n )\n\n @Entity\n data class Playlist(\n @PrimaryKey val playlistId: Long,\n val userCreatorId: Long,\n val playlistName: String\n )\n\n @Entity\n data class Song(\n @PrimaryKey val songId: Long,\n val songName: String,\n val artist: String\n )\n\n @Entity(primaryKeys = [\"playlistId\", \"songId\"])\n data class PlaylistSongCrossRef(\n val playlistId: Long,\n val songId: Long\n )\n\n### Java\n\n @Entity\n public class User {\n @PrimaryKey public long userId;\n public String name;\n public int age;\n }\n\n @Entity\n public class Playlist {\n @PrimaryKey public long playlistId;\n public long userCreatorId;\n public String playlistName;\n }\n @Entity\n public class Song {\n @PrimaryKey public long songId;\n public String songName;\n public String artist;\n }\n\n @Entity(primaryKeys = {\"playlistId\", \"songId\"})\n public class PlaylistSongCrossRef {\n public long playlistId;\n public long songId;\n }\n\nFirst, model the relationship between two of the tables in your set as you\nnormally do, using a data class and the [`@Relation`](/reference/kotlin/androidx/room/Relation) annotation. The\nfollowing example shows a `PlaylistWithSongs` class that models a many-to-many\nrelationship between the `Playlist` entity class and the `Song` entity class: \n\n### Kotlin\n\n data class PlaylistWithSongs(\n @Embedded val playlist: Playlist,\n @Relation(\n parentColumn = \"playlistId\",\n entityColumn = \"songId\",\n associateBy = Junction(PlaylistSongCrossRef::class)\n )\n val songs: List\u003cSong\u003e\n )\n\n### Java\n\n public class PlaylistWithSongs {\n @Embedded public Playlist playlist;\n @Relation(\n parentColumn = \"playlistId\",\n entityColumn = \"songId\",\n associateBy = Junction(PlaylistSongCrossRef.class)\n )\n public List\u003cSong\u003e songs;\n }\n\nAfter you define a data class that represents this relationship, create another\ndata class that models the relationship between another table from your set and\nthe first relationship class, \"nesting\" the existing relationship within the new\none. The following example shows a `UserWithPlaylistsAndSongs` class that models\na one-to-many relationship between the `User` entity class and the\n`PlaylistWithSongs` relationship class: \n\n### Kotlin\n\n data class UserWithPlaylistsAndSongs(\n @Embedded val user: User\n @Relation(\n entity = Playlist::class,\n parentColumn = \"userId\",\n entityColumn = \"userCreatorId\"\n )\n val playlists: List\u003cPlaylistWithSongs\u003e\n )\n\n### Java\n\n public class UserWithPlaylistsAndSongs {\n @Embedded public User user;\n @Relation(\n entity = Playlist.class,\n parentColumn = \"userId\",\n entityColumn = \"userCreatorId\"\n )\n public List\u003cPlaylistWithSongs\u003e playlists;\n }\n\nThe `UserWithPlaylistsAndSongs` class indirectly models the relationships\nbetween all three of the entity classes: `User`, `Playlist`, and `Song`. This is\nillustrated in figure 1.\n**Figure 1.** Diagram of relationship classes in the music streaming app example.\n\nIf there are any more tables in your set, create a class to model the\nrelationship between each remaining table and the relationship class that models\nthe relationships between all previous tables. This creates a chain of nested\nrelationships among all the tables that you want to query.\n\nFinally, add a method to the DAO class to expose the query function that your\napp needs. This method requires Room to run multiple queries, so add the\n[`@Transaction`](/reference/kotlin/androidx/room/Transaction) annotation so that the whole operation is performed\natomically: \n\n### Kotlin\n\n @Transaction\n @Query(\"SELECT * FROM User\")\n fun getUsersWithPlaylistsAndSongs(): List\u003cUserWithPlaylistsAndSongs\u003e\n\n### Java\n\n @Transaction\n @Query(\"SELECT * FROM User\")\n public List\u003cUserWithPlaylistsAndSongs\u003e getUsersWithPlaylistsAndSongs();"]]