In Room, how do you load each artist with all of their albums through @Relation, and why does that DAO function need @Transaction?
answer
- a result class, not an entity
- @Embedded parent plus a list
- parent keys matched to child column
- two queries, one consistent snapshot
basics
~20 sRoom fills a result class pairing an @Embedded Artist with a @Relation List<Album> matched on artistId. Room runs the artist query and then a separate album query, so @Transaction keeps both reads on one consistent database state.
solid answer
~40 sYou write a plain result class, not an entity: `@Embedded val artist: Artist` plus `@Relation(parentColumns = ["artistId"], entityColumns = ["artistOwnerId"]) val albums: List<Album>` in Room 3.0 (Room 2.x spells them `parentColumn = "artistId"`, `entityColumn = "artistOwnerId"`). The DAO's `@Query` selects only from `Artist`; Room runs it, collects the artist keys, then runs a second query on `Album` with those keys and attaches each album to its artist. Because those are two statements, a write landing between them could pair artists with albums from a different state, so you annotate the function `@Transaction`. Without it Room still builds, but reports the `RELATION_QUERY_WITHOUT_TRANSACTION` warning. `@Relation` cannot sit on an `@Entity`, and it has no ordering or filtering of the children.
code
kotlin · 15 linesdata class ArtistWithAlbums(
@Embedded val artist: Artist,
@Relation(
parentColumns = ["artistId"],
entityColumns = ["artistOwnerId"]
)
val albums: List<Album>
)
@Dao
interface ArtistDao {
@Transaction
@Query("SELECT * FROM Artist ORDER BY name")
suspend fun artistsWithAlbums(): List<ArtistWithAlbums>
}go deeper
Recall the pattern: a result class with an @Embedded parent and a @Relation list of children, returned from a @Query that selects the parent table.
Explain the two queries Room runs, which column goes in parentColumns versus entityColumns, and why @Transaction keeps both reads on one snapshot.
Show the limits you hit in production: no ordering or filtering of children, the warning-not-error on a missing @Transaction, and rewriting every relation for Room 3.0's arrays.
Weigh relation result classes against join queries as the team's default read shape, considering consistency, child ordering and how much each screen actually loads.
## The shape Room expects Room does not let one entity hold a reference to another. To read an artist together with the albums that belong to them, you describe the pairing in a separate **result class** and let Room fill it. In a music library where each `Album` row stores its artist's id in `artistOwnerId`: - The parent is an **`@Embedded`** property of the parent entity type: `@Embedded val artist: Artist`. It receives the columns of each row the DAO query returns. - The children are a **`@Relation`** property typed `List<Album>` (or `Set<Album>`). A one-to-one relation uses a single object instead of a collection. - **`parentColumns`** names the column on the parent side, **`entityColumns`** the matching column on the child entity. Room infers the child entity from the list's element type; `entity = Album::class` lets you return a smaller class instead, and `projection` picks which child columns are read. - The class is **not** an `@Entity`. Room allows `@Relation` only in non-entity result classes, by design, so that no entity ever carries a hidden link to another table. ## Room 3.0 versus Room 2.x spelling | | Room 3.0 (`androidx.room3`) | Room 2.x (`androidx.room`) | |---|---|---| | Parent side | `parentColumns = ["artistId"]` (array) | `parentColumn = "artistId"` (one string) | | Child side | `entityColumns = ["artistOwnerId"]` (array) | `entityColumn = "artistOwnerId"` (one string) | | Why it changed | arrays allow composite relationship keys (3.0.0-alpha05) | single-column keys only | | DAO function | `suspend`, or a reactive type such as `Flow` | `suspend`, reactive, or blocking | Moving a codebase from 2.x to 3.0 means rewriting every `@Relation` to the array form; the move itself is covered in the lesson on Room entities and the 3.0 setup. ## What Room runs when you call the function Your `@Query` only mentions the parent table, for example `SELECT * FROM Artist ORDER BY name`. Room's generated code then: 1. Runs that query and builds the `@Embedded` `Artist` for each row, collecting every `artistId` it sees. 2. Runs a **second query** against `Album`, selecting rows whose `artistOwnerId` is among the collected keys. With a very large parent result, Room splits the keys into batches of at most 999, one query per batch. 3. Groups the albums by key and hands each artist its list. An artist with no albums gets an empty list. So the relation costs a fixed handful of queries, not one per artist, and every album is loaded immediately. There is no lazy property that fetches albums later. ## Why `@Transaction` is required in practice Between step 1 and step 2 another coroutine or a sync job may write. Without a transaction, you could read the artist list before an album is moved to a different artist and the album rows after it, and the result would describe a state that never existed. `@Transaction` on the DAO function makes Room run the generated code, both queries included, inside one database transaction, so both reads see the same snapshot. - Leaving it out is **not** a build error. Room reports the **`RoomWarnings.RELATION_QUERY_WITHOUT_TRANSACTION`** warning and generates the function anyway. - For a function that returns a `Flow`, Room applies the transaction **each time the query runs**, not when the function is called. - The examples in Room's relationship guides put `@Transaction` on each relation query for exactly this reason: the function requires Room to run more than one query. ## What `@Relation` cannot do - **Order or filter the children.** The annotation's parameters are `entity`, `parentColumns`, `entityColumns`, `associateBy` and `projection`; nothing sets an `ORDER BY` or a `WHERE` on the child query. Sort the list in Kotlin, or write a join query that returns a multimap when SQL must order or filter the children. - **Live on an entity.** Putting `@Relation` inside `Artist` is rejected; keep entities flat and compose them in result classes. - **Replace an index.** The child lookup filters on `artistOwnerId`, so that column wants an index; declaring it belongs with Room's entity and foreign-key annotations. ## Putting it together The relation class, the DAO function and the transaction are three separate decisions an interviewer looks for: a result class instead of an object reference, the right column on each side in the major you use, and `@Transaction` because Room's relation read is more than one statement.
- The album list must be newest first. Can `@Relation` sort it?No. `@Relation` has no parameter for ordering or filtering the children; the `ORDER BY` in your `@Query` orders only the artists. Sort `albums` in Kotlin after loading, or replace the relation with a join query returning `Map<Artist, List<Album>>` whose `ORDER BY` covers album columns too.
- The screen needs only album titles, not whole `Album` rows. What do you change?Set `entity = Album::class` on the `@Relation` and type the property as a list of a smaller data class holding only the needed columns, or set `entity = Album::class` with `projection = ["title"]` and type the property `List<String>`. Room then selects only those columns in the child query.
- The DAO function returns `Flow<List<ArtistWithAlbums>>`. When does `@Transaction` take effect?Each time Room runs the query for an emission, both the artist query and the album query run inside one transaction. The annotation is applied when the query runs, not when the function is called and the `Flow` is created.
- Put a List<Album> property with @Relation directly on the Artist entity
- Room loads each artist's albums lazily when the list is first accessed
- Without @Transaction the relation query fails to compile
- @Relation runs one JOIN query, so a transaction adds nothing
- The ORDER BY in the parent query also orders each artist's albums
Assumes Room 3.0, where @Relation takes parentColumns and entityColumns arrays (3.0.0-alpha05); Room 2.x spells them parentColumn and entityColumn as single strings.