skip to content

Relations and Embedded

@Embedded to flatten objects into a row, @Relation for one-to-many and many-to-many reads through junctions, and multimap results. Asked because Room has no lazy loading, so you explain the queries.

on this pageshow

explore

questions

6

In Room, how do you load each artist with all of their albums through @Relation, and why does that DAO function need @Transaction?

level: middleimportance: must knowfreq 62%

answer

  1. a result class, not an entity
  2. @Embedded parent plus a list
  3. parent keys matched to child column
  4. two queries, one consistent snapshot

basics

~20 s

Room 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 s

You 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 lines
kotlin
data 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

for a junior

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.

for a middle

Explain the two queries Room runs, which column goes in parentColumns versus entityColumns, and why @Transaction keeps both reads on one snapshot.

for a senior

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.

for a principal

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.

open as a page

In Room, what does @Embedded do to an entity's table, and when do you need its prefix parameter?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Room's @Embedded flattens a value object's properties into columns of the containing entity's own table. When two embedded properties share a type, their column names collide, so prefix prepends a distinct string to every column of one of them.

open as a page

In Room, how do you read each playlist with its songs when playlists share songs, using @Relation with a @Junction cross-reference entity?

level: middleimportance: should knowfreq 45%

basics

~10 s

Room 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.

open as a page

In Room, when would you return Map<Artist, List<Album>> from a JOIN query instead of an @Relation result class?

level: middleimportance: should knowfreq 28%

basics

~20 s

Room's multimap return type groups one JOIN query's rows into a Map, so SQL can filter, order and aggregate across both tables. Choose it when the screen needs that, or a count via @MapColumn; choose @Relation for nested reads without hand-written joins.

open as a page

Room has no lazy loading: when a music app reads artists with their albums and each album's songs through nested @Relation classes, how many queries run, and what does that cost?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Room reads the whole artist, album and song graph eagerly: one parent query, then one query per relation level for each batch of up to 999 keys. It avoids one query per row, but loads every child row whether the screen shows it or not.

open as a page

In Room 3.0, how does @Relation join a child entity to a parent with a composite key, and what did Room 2.x apps do instead?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

Room 3.0 lists every key column in @Relation's parentColumns and entityColumns arrays, paired by position, and Junction takes arrays too. Room 2.x accepted one column per side, so apps used a single surrogate key or a hand-written JOIN.

open as a page