In Room, how do you read each playlist with its songs when playlists share songs, using @Relation with a @Junction cross-reference entity?
answer
- a third table holds the pairs
- the cross-reference is a real entity
- associateBy names the junction
- junction columns default to the relation's
basics
~10 sRoom needs a cross-reference entity holding playlistId and songId pairs, and a result class whose @Relation sets associateBy = Junction(PlaylistSongCrossRef::class). Room reads the songs through that junction table; the DAO function needs @Transaction.
solid answer
~40 sSongs carry no playlist column, so you add a cross-reference `@Entity`, `PlaylistSongCrossRef(playlistId, songId)` with both columns as its composite primary key, and list it in `@Database`. The result class is `@Embedded val playlist: Playlist` plus `@Relation(parentColumns = ["playlistId"], entityColumns = ["songId"], associateBy = Junction(PlaylistSongCrossRef::class)) val songs: List<Song>` in Room 3.0. `Junction`'s own `parentColumns` and `entityColumns` default to the relation's; set them when the cross-reference names its columns differently. The reverse read, songs with their playlists, swaps the two sides over the same junction. The DAO function is `@Transaction` because Room reads the parents and the songs with separate queries, and Room warns with `MISSING_INDEX_ON_JUNCTION` when a junction column it looks up is not covered by an index.
code
kotlin · 25 lines@Entity(
primaryKeys = ["playlistId", "songId"],
indices = [Index("songId")]
)
data class PlaylistSongCrossRef(
val playlistId: Long,
val songId: Long
)
data class PlaylistWithSongs(
@Embedded val playlist: Playlist,
@Relation(
parentColumns = ["playlistId"],
entityColumns = ["songId"],
associateBy = Junction(PlaylistSongCrossRef::class)
)
val songs: List<Song>
)
@Dao
interface PlaylistDao {
@Transaction
@Query("SELECT * FROM Playlist")
suspend fun playlistsWithSongs(): List<PlaylistWithSongs>
}go deeper
Recall that many-to-many needs a cross-reference entity holding pairs of keys, and that the relation names it with associateBy = Junction(...).
Explain how Junction's columns default to the relation's, when to set them, how the reverse direction is declared, and why the read needs @Transaction.
Show the production details: indexing the junction for both directions, matching key types, and dropping to a join query when order or junction attributes matter.
Decide when junction attributes such as position or addedAt make the cross-reference a first-class entity read by join queries rather than through @Relation.
## Why many-to-many needs a third table In a music app a playlist holds many songs, and the same song appears in many playlists. Neither table can hold the link: a `Song` row has room for one playlist id, not many. The standard answer is an **associative entity**, also called a cross-reference or junction table, where each row records one pairing. In Room that table is an ordinary `@Entity`, listed in `@Database(entities = [...])` like any other: - It has a column for the primary key of each side: `playlistId` and `songId`. - Its primary key is usually the pair, `primaryKeys = ["playlistId", "songId"]`, so the same song cannot be added to one playlist twice. - Adding a song to a playlist is inserting a row into it; removing one is deleting that row. Those writes are ordinary DAO functions. ## Declaring the relation The read side is a result class, as for one-to-many, with one extra argument: | Parameter | Meaning here | |---|---| | `parentColumns = ["playlistId"]` | the key on the parent, `Playlist` | | `entityColumns = ["songId"]` | the key on the child entity, `Song` | | `associateBy = Junction(PlaylistSongCrossRef::class)` | the table that pairs them | | `Junction(..., parentColumns = [...])` | the junction's column matched to the parent key; defaults to the relation's `parentColumns` | | `Junction(..., entityColumns = [...])` | the junction's column matched to the child key; defaults to the relation's `entityColumns` | Because the junction's columns default to the relation's names, a cross-reference that reuses `playlistId` and `songId` needs only `Junction(PlaylistSongCrossRef::class)`. If it calls them `pId` and `sId`, write `Junction(value = PlaylistSongCrossRef::class, parentColumns = ["pId"], entityColumns = ["sId"])`. The `value` may also be a `@DatabaseView`. The **reverse direction** is a second result class, `SongWithPlaylists(@Embedded val song: Song, @Relation(parentColumns = ["songId"], entityColumns = ["playlistId"], associateBy = Junction(PlaylistSongCrossRef::class)) val playlists: List<Playlist>)`, over the same junction. ## Room 3.0 versus Room 2.x - **Room 3.0** (`androidx.room3`): `parentColumns` and `entityColumns` are arrays on both `@Relation` and `Junction`, which is what lets a relation use a composite key (3.0.0-alpha05). - **Room 2.x** (`androidx.room`): `Junction(value, parentColumn, entityColumn)` and `@Relation(parentColumn, entityColumn, associateBy)` take single strings. `associateBy` and `Junction` arrived in Room 2.2.0. ## What Room runs and what to annotate Calling `@Transaction @Query("SELECT * FROM Playlist") suspend fun playlistsWithSongs(): List<PlaylistWithSongs>` makes Room run your playlist query, collect the playlist keys and then fetch the matching songs through the junction table, in batches of at most 999 keys. That is more than one statement, so: 1. Annotate the function with **`@Transaction`**, so a concurrent insert into the cross-reference cannot land between the reads. Without it Room only warns (`RELATION_QUERY_WITHOUT_TRANSACTION`). 2. **Index the junction columns** the relation looks up. Room reports `RoomWarnings.MISSING_INDEX_ON_JUNCTION` when such a column is not covered by any index, because the lookup might then scan the whole table. The composite primary key `(playlistId, songId)` serves lookups by `playlistId`; the reverse read by `songId` wants `Index("songId")`. 3. **Keep key types aligned.** When a relation's child column type does not match the parent's, Room reports `RELATION_TYPE_MISMATCH` and falls back to matching on `String` representations. ## Where `@Relation` stops Real playlists have an order, and the cross-reference is where it lives: a `position` column per pairing. `@Relation` cannot use it: - it returns `Song` rows only, so junction columns such as `position` or `addedAt` are not exposed; - it has no parameter to order the child list, and the `ORDER BY` in the parent query orders only the playlists. When the order or a junction attribute matters, write the join yourself: `SELECT Playlist.*, Song.* FROM Playlist JOIN PlaylistSongCrossRef ... JOIN Song ... ORDER BY position`, returned as a multimap or a flat result class. Room's documentation says as much: when `@Relation` does not fit, use a `JOIN` query. ## Mistakes that show up in review - **Treating the relation as writable.** `PlaylistWithSongs` is read-only; adding a song to a playlist is an insert into the cross-reference, and removing it is a delete there. - **Leaving the cross-reference out of the database.** It is a table like any other, so it must be listed in `@Database(entities = [...])` before Room can use it as a junction. - **Forgetting orphans.** Deleting a song leaves its cross-reference rows behind unless a foreign key with a cascading delete removes them; declaring that belongs with Room's entity annotations. - **One class for both directions.** Each direction is its own result class with the parent and child sides swapped.
- The cross-reference table names its columns `pId` and `sId`. What changes in the relation?The `@Relation` keeps the entities' key names, `parentColumns = ["playlistId"]` and `entityColumns = ["songId"]`, and the `Junction` maps its own columns: `Junction(value = PlaylistSongCrossRef::class, parentColumns = ["pId"], entityColumns = ["sId"])`. Left out, the junction would default to the relation's names, `playlistId` and `songId`, which the cross-reference does not have.
- Songs must come back in the order stored in the cross-reference's `position` column. Can the relation do it?No. `@Relation` returns only `Song` rows and has no ordering parameter, and the parent query's `ORDER BY` orders playlists. Write a join over the cross-reference ordered by `position` and return a multimap or a result class that carries the position.
- Add a playlistIds list column to Song to model many-to-many
- The cross-reference class need not be listed in @Database entities
- Junction columns must always be spelled out even when names match
- projection on @Relation can read the junction's position column
- A composite primary key on the junction indexes both lookup directions
Assumes Room 3.0, where @Relation and Junction take parentColumns and entityColumns arrays (3.0.0-alpha05); Room 2.x uses single-string parentColumn and entityColumn.