skip to content

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

level: juniorimportance: should knowfreq 45%

answer

  1. no second table, no join
  2. the value object's fields become columns
  3. two properties of one type collide
  4. prefix lands even on renamed columns

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.

solid answer

~40 s

`@Embedded` tells Room to treat the properties of a plain class as if they were declared on the containing class. On an `@Entity` they become columns of the same table, so there is no second table, no join and no foreign key, and queries can filter on them directly. If an `Album` holds two `Artwork` values, both would produce `url`, `widthPx` and `heightPx`, so Room rejects the entity; `@Embedded(prefix = "cover_")` and `@Embedded(prefix = "thumb_")` keep the columns apart. The prefix applies to every sub-column, even one renamed with `@ColumnInfo(name = ...)`. A nullable embedded property comes back `null` when all of its columns are `NULL`, and a `@PrimaryKey` or `@ColumnInfo(index = true)` inside the embedded class is dropped with a warning.

code

kotlin · 16 lines
kotlin
data class Artwork(
    val url: String?,
    val widthPx: Int?,
    val heightPx: Int?
)

@Entity
data class Album(
    @PrimaryKey val albumId: Long,
    val title: String,
    @Embedded(prefix = "cover_") val cover: Artwork,
    @Embedded(prefix = "thumb_") val thumbnail: Artwork?
)
// Album table columns: albumId, title,
// cover_url, cover_widthPx, cover_heightPx,
// thumb_url, thumb_widthPx, thumb_heightPx

go deeper

for a junior

Recall that @Embedded flattens a value object into columns of the same table, and that prefix keeps two embedded properties of one type from colliding.

for a middle

Explain the column names Room derives, that the prefix applies even to @ColumnInfo names, and the all-NULL rule for nullable embedded properties.

for a senior

Show you know what silently disappears: primary keys and indexes declared inside the embedded class, and that renaming a prefix is a schema change needing a migration.

for a principal

Frame when a value object deserves real columns via @Embedded rather than one serialized column, weighing filtering and indexing against schema churn.

## What `@Embedded` does Room maps every `@Entity` class to one SQLite table, one column per property. Sometimes a group of properties belongs together without deserving a table of its own: an album's cover art has a URL, a width and a height, and nothing else in the database points at it. Room's `@Embedded` annotation handles that case. It marks a property whose class is **not** an entity and tells Room to treat that class's properties as if they were declared directly on the containing class. - On an **`@Entity`**, the embedded class's properties become **columns of the same table**. There is no second table, no join and no foreign key. - On a **plain result class** (the return type of a `@Query`), Room reads those properties from the result columns of the query. - Queries refer to the flattened columns directly, so `WHERE cover_url IS NULL` works like any other filter. - An embedded class can itself contain `@Embedded` properties; the flattening repeats at each level. - When reading a row, Room builds the embedded object from its columns and passes it to the containing class, just as it does for plain properties. The annotation lives in `androidx.room3` in Room 3.0 and in `androidx.room` in Room 2.x; it behaves the same way in both. ## Why `prefix` exists Take a music library's `Album` entity that stores two pieces of artwork, the cover and a small thumbnail, both of type `Artwork(url, widthPx, heightPx)`. Without help, both properties would produce columns named `url`, `widthPx` and `heightPx`. Two properties cannot map to one column, so Room's annotation processor rejects the entity at build time. `@Embedded(prefix = "...")` solves it. The **prefix** (an empty string by default) is prepended to the name of every column that comes from the embedded class: | Declaration | Columns in the `Album` table | |---|---| | `@Embedded(prefix = "cover_") val cover: Artwork` | `cover_url`, `cover_widthPx`, `cover_heightPx` | | `@Embedded(prefix = "thumb_") val thumbnail: Artwork?` | `thumb_url`, `thumb_widthPx`, `thumb_heightPx` | Two details matter in interviews: 1. **The prefix always applies**, even to a sub-property that carries `@ColumnInfo(name = "img_url")`; with `prefix = "cover_"` that column is `cover_img_url`. 2. **The prefix is part of the schema.** Renaming it later renames columns, which is a schema change that needs a migration (covered in the lesson on Room's migrations). ## Nullable embedded properties An embedded property may be nullable. When Room reads a row, it checks every column that belongs to the embedded object (including its own nested embedded objects): - If **all of them are `NULL`**, the property is set to `null` and the object is not constructed. - If **any of them has a value**, Room constructs the object. - A **non-null** embedded property is always constructed. The rule has a sharp edge. If a column converter would turn `NULL` into a non-null value, it is never consulted in the all-`NULL` case, because Room does not build the object at all. And an `Artwork` whose fields are all nullable and all empty in a legitimate row comes back as `null`, not as an empty `Artwork`. If the screen must tell "no thumbnail" from "a thumbnail with no data yet", model that difference explicitly. ## What does not carry over Annotations that make sense on an entity lose their meaning inside an embedded class, and Room says so at build time: - A `@PrimaryKey` on a sub-property is **dropped**; Room reports the `RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED` warning. The containing entity declares its own key. - `@ColumnInfo(index = true)` on a sub-property is **dropped** with `RoomWarnings.INDEX_FROM_EMBEDDED_FIELD_IS_DROPPED`; declare the index on the containing entity instead (index declarations are covered with Room's entities). ## Where else `@Embedded` appears `@Embedded` is also the parent half of every relation result class. In `ArtistWithAlbums(@Embedded val artist: Artist, @Relation(...) val albums: List<Album>)`, the `@Embedded` property receives the columns of the parent query's rows, and `@Relation` fills the child list. It is also how a query that selects columns from a join maps part of each row onto an existing class. ## `@Embedded` versus a single serialized column Storing the artwork as one text column through a column converter is the other way to keep a value object in a row. `@Embedded` keeps each field as a real column you can filter, sort and index; a serialized column hides the fields from SQL. That choice is covered in the lesson on Room's type converters.

  • What does Room return for `thumbnail` when every `thumb_` column in the row is NULL?
    Because `thumbnail` is declared nullable, Room sets it to `null` and never constructs an `Artwork`, even if a column converter could turn `NULL` into a value. If any `thumb_` column has a value, Room builds the object. A non-null embedded property is always constructed.
  • The `Artwork` class marks `url` with `@PrimaryKey`. What happens when it is embedded in `Album`?
    Room drops that primary key while flattening the class into `Album` and reports the `PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED` warning. The entity's own key, `albumId`, stays the only primary key; `cover_url` is an ordinary column.

  • @Embedded creates a separate table joined to the entity by a foreign key
  • Room numbers duplicate column names automatically, so prefix is cosmetic
  • @ColumnInfo(name) on a sub-property overrides the embedded prefix
  • When all its columns are NULL, a nullable embedded property becomes an object of nulls
  • A @PrimaryKey inside an embedded class becomes part of the entity's key