Stay organized with collections
Save and categorize content based on your preferences.
Sometimes, you might need to query a set of three or more tables that are all
related to each other. In that case, you define nested relationships between
the tables.
Suppose that in the music streaming app example, you want to query all the
users, all the playlists for each user, and all the songs in each playlist for
each user. Users have a one-to-many relationship with playlists, and
playlists have a many-to-many relationship with songs. The following code
example shows the classes that represent these entities as well as the
cross-reference table for the many-to-many relationship between playlists and
songs:
First, model the relationship between two of the tables in your set as you
normally do, using a data class and the @Relation annotation. The
following example shows a PlaylistWithSongs class that models a many-to-many
relationship between the Playlist entity class and the Song entity class:
After you define a data class that represents this relationship, create another
data class that models the relationship between another table from your set and
the first relationship class, "nesting" the existing relationship within the new
one. The following example shows a UserWithPlaylistsAndSongs class that models
a one-to-many relationship between the User entity class and the
PlaylistWithSongs relationship class:
The UserWithPlaylistsAndSongs class indirectly models the relationships
between all three of the entity classes: User, Playlist, and Song. This is
illustrated in figure 1.
Figure 1. Diagram of relationship classes in the
music streaming app example.
If there are any more tables in your set, create a class to model the
relationship between each remaining table and the relationship class that models
the relationships between all previous tables. This creates a chain of nested
relationships among all the tables that you want to query.
Finally, add a method to the DAO class to expose the query function that your
app needs. This method requires Room to run multiple queries, so add the
@Transaction annotation so that the whole operation is performed
atomically:
Kotlin
@Transaction@Query("SELECT * FROM User")fungetUsersWithPlaylistsAndSongs():List<UserWithPlaylistsAndSongs>
Java
@Transaction@Query("SELECT * FROM User")publicList<UserWithPlaylistsAndSongs>getUsersWithPlaylistsAndSongs();
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2025-02-10 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-02-10 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();"]]