skip to content

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%

answer

  1. single strings became arrays
  2. column order pairs them up
  3. Junction got the same change
  4. 2.x needed one surrogate key

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.

solid answer

~40 s

Room 3.0.0-alpha05 turned `@Relation`'s `parentColumn` and `entityColumn` strings into the `parentColumns` and `entityColumns` arrays, and did the same on `Junction`. An `Album` keyed by `primaryKeys = ["labelCode", "catalogNumber"]` now relates to its tracks with `parentColumns = ["labelCode", "catalogNumber"]` and `entityColumns = ["albumLabelCode", "albumCatalogNumber"]`; the order must match, because Room pairs columns by position. Room 2.x took exactly one column per side, so a composite parent needed a single surrogate key the children referenced, or a hand-written join into a multimap or flat result. Moving to 3.0 means rewriting every relation to the array form even for single columns, but it is a compile-time change only: `@Relation` describes reads and creates no table or column, so it needs no schema migration.

code

kotlin · 23 lines
kotlin
@Entity(primaryKeys = ["labelCode", "catalogNumber"])
data class Album(
    val labelCode: String,
    val catalogNumber: String,
    val title: String
)

@Entity
data class Track(
    @PrimaryKey val trackId: Long,
    val albumLabelCode: String,
    val albumCatalogNumber: String,
    val title: String
)

data class AlbumWithTracks(
    @Embedded val album: Album,
    @Relation(
        parentColumns = ["labelCode", "catalogNumber"],
        entityColumns = ["albumLabelCode", "albumCatalogNumber"]
    )
    val tracks: List<Track>
)

go deeper

for a junior

Recall that Room 3.0's @Relation takes arrays, parentColumns and entityColumns, where Room 2.x took one column name per side.

for a middle

Explain how Room pairs the columns by position, how Junction's arrays default to the relation's, and why the read keeps @Transaction.

for a senior

Show the migration view: every relation rewritten to arrays when moving to 3.0, no schema change for that, and the 2.x surrogate-key workaround left in place.

for a principal

Judge whether new entities should use natural composite keys now that relations allow them, or keep single surrogate keys for uniformity and simpler references.

## The change Some parents are naturally identified by more than one column. A music catalogue may key an album by its **label code** and **catalogue number**, `@Entity(primaryKeys = ["labelCode", "catalogNumber"])`, and each track stores both values to point at its album. Relating the two needs a join on **two columns at once**. Room 3.0 supports that directly. In **3.0.0-alpha05** the `@Relation` and `@Junction` annotations changed: | Annotation | Room 2.x (`androidx.room`) | Room 3.0 (`androidx.room3`) | |---|---|---| | `@Relation` parent side | `parentColumn: String` | `parentColumns: Array<String>` | | `@Relation` child side | `entityColumn: String` | `entityColumns: Array<String>` | | `Junction` parent side | `parentColumn: String = ""` | `parentColumns: Array<String> = []` | | `Junction` child side | `entityColumn: String = ""` | `entityColumns: Array<String> = []` | The Room 3.0 release notes list "composite relationship column with `@Relation`" among the features 3.0.0 brought over 2.x. ## Declaring a composite relation in Room 3.0 - List **every key column** on each side, in the **same order**: Room pairs `parentColumns[0]` with `entityColumns[0]`, `parentColumns[1]` with `entityColumns[1]`, and so on. Swapping the order on one side pairs the wrong columns. - Keep the **types aligned** pairwise. If a parent column and its child column have different SQLite types, Room reports `RoomWarnings.RELATION_TYPE_MISMATCH` and falls back to matching on `String` representations. - The child's referencing columns want an index for the lookup; declaring it belongs with Room's entity annotations. - For **many-to-many**, the relation's arrays name the keys on the two entities and, when the cross-reference spells its columns differently, `Junction(value = ..., parentColumns = [...], entityColumns = [...])` names the junction's columns. Left empty, the junction arrays default to the relation's. Room's guide shows a playlist keyed by `playlistId` and `creatorId` relating to songs through a three-column cross-reference. - The read still runs the parent query and then separate child queries, so the DAO function keeps its **`@Transaction`**. ## What Room 2.x apps did In Room 2.x a relation could match exactly **one** column per side. Teams with composite parents worked around it in one of these ways: 1. **A surrogate key.** Give the parent a single `@PrimaryKey(autoGenerate = true) val albumId: Long`, keep the natural columns under a unique index, and let children reference `albumId`. This is the most common fix, and still a sound design in 3.0. 2. **A hand-written join.** Join on both columns in a `@Query` and return a multimap such as `Map<Album, List<Track>>` or a flat result class, giving up `@Relation`'s automatic fetching. 3. **A concatenated key column.** Store `"$labelCode:$catalogNumber"` in an extra column on both sides. It works, but it duplicates data that must be kept in step by every write. ## Moving existing relations to 3.0 When a codebase moves from Room 2.x to 3.0, every relation changes form even if it never used a composite key: `@Relation(parentColumn = "artistId", entityColumn = "artistOwnerId")` becomes `@Relation(parentColumns = ["artistId"], entityColumns = ["artistOwnerId"])`, and `Junction`'s named columns change the same way. The move as a whole (the new package, the driver, KSP) is covered with Room's entities and 3.0 setup. What matters here: - It is a **source change caught at build time**: the old parameter names no longer exist. - It needs **no schema migration**: `@Relation` and `Junction` describe how Room reads; they create no table, column or index, so the database version does not change. - A surrogate key added only as a 2.x workaround can stay. Dropping it to use the natural composite key is a real schema change with a migration of its own. ## A checklist for a composite relation Before shipping a relation on a composite key in Room 3.0, check it the way a reviewer would: 1. **Same length.** `parentColumns` and `entityColumns` list the same number of columns, one child column per parent key column. 2. **Same order.** The arrays pair by position, so `labelCode` sits opposite `albumLabelCode` and `catalogNumber` opposite `albumCatalogNumber`. 3. **Same types.** Each pair shares a column type; otherwise Room warns with `RELATION_TYPE_MISMATCH` and compares `String` forms. 4. **An index on the child columns.** The child query filters on both referencing columns, so the child entity declares an index covering them. 5. **`@Transaction` on the DAO function.** The parent and child reads are still separate statements. 6. **A test with real keys.** A fixture where two albums share a label code but differ in catalogue number proves the second column takes part in the match.

  • Does rewriting `parentColumn` to `parentColumns` during the move to Room 3.0 need a database version bump?
    No. `@Relation` and `Junction` only describe how Room reads related rows; they create no table, column or index, so the schema and its version are unchanged. The old single-string parameters simply no longer compile in Room 3.0.
  • A Room 2.x app added a surrogate `albumId` only because relations needed one column. Should the 3.0 move drop it?
    Not as part of the move. A single surrogate key remains a sound design, and dropping it changes the schema of the parent and every child, which needs its own migration and tests. Use composite relations for new entities whose natural key is genuinely composite.

  • Room 2.x could relate composite keys with a comma-separated parentColumn
  • Column order in parentColumns and entityColumns does not matter
  • Switching @Relation to arrays requires a schema migration
  • Room 3.0 still accepts the single-string parentColumn parameter
  • Junction keeps single-string columns in Room 3.0

Composite relationship columns exist only in Room 3.0 (parentColumns and entityColumns arrays since 3.0.0-alpha05); Room 2.x's @Relation and Junction match a single column per side.