skip to content

Entities and Schema

@Entity, @PrimaryKey, @ColumnInfo, indices and foreign keys, and the SQLite table DDL Room generates from them. Interviewers check that you know you are defining a table, not decorating a data class.

on this pageshow

explore

questions

6

In Room, what does annotating a Kotlin data class with @Entity declare, and how does @Database tie the entities together?

level: juniorimportance: must knowfreq 80%

answer

  1. a table, not a model
  2. class and property names by default
  3. every entity needs a primary key
  4. entities list plus a version
  5. generated _Impl, checked at build time

basics

~20 s

@Entity declares a SQLite table: one table per class, one column per persisted property, keyed by its @PrimaryKey. @Database lists those entity classes with a schema version, and Room's compiler generates the database that creates and checks the tables.

solid answer

~40 s

An `@Entity` class is a table definition. Room's annotation processor turns it into a `CREATE TABLE` with one column per persisted property, named after the class (or `tableName`) and the properties (or `@ColumnInfo(name = ...)`). Every entity needs a primary key, from `@PrimaryKey` or `@Entity(primaryKeys = ...)`, and `@Ignore` keeps a property out of the table. An abstract `RoomDatabase` subclass annotated `@Database(entities = [...], version = N)` ties them together: only the listed entities become tables, and the processor generates the implementation that creates them on first open, plus DAO code whose SQL it checks against them at build time. `version` is the schema version: Room stores a hash of the schema in the file, and a changed entity with an unchanged version fails on open with an `IllegalStateException`.

code

kotlin · 12 lines
kotlin
@Entity(tableName = "recipes")
data class Recipe(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val title: String,
    @ColumnInfo(name = "prep_minutes") val prepMinutes: Int,
) {
    @Ignore
    var isExpanded: Boolean = false
}

@Database(entities = [Recipe::class], version = 1)
abstract class RecipeDatabase : RoomDatabase()

go deeper

for a junior

Say that @Entity defines a table, name the default table and column names, and that every entity needs a primary key and a place in @Database(entities).

for a middle

Explain what the processor generates from the declarations, how it matches a constructor to the columns, and why ignored constructor parameters need default values.

for a senior

Show how entity edits become schema changes on users' devices: pinned table and column names, the identity hash in room_master_table, and the exception a forgotten version bump causes.

for a principal

Treat entity classes as a persisted contract: agree which edits are free, which need a migration, and how code review catches schema changes before a release.

## An entity is a table definition Room is Android's compile-checked layer over SQLite. Annotating a class with **`@Entity`** does not mark a model for serialization; it writes a **table definition** in Kotlin. Room's annotation processor reads the class at build time and generates the SQL that creates the table: - the **table name** is the class name unless you set `@Entity(tableName = "recipes")`; - each **persisted property** becomes a column, named after the property unless `@ColumnInfo(name = "prep_minutes")` renames it; - the **column type** follows the Kotlin type (`Int`, `Long` and `Boolean` become `INTEGER`, `String` becomes `TEXT`, `Double` becomes `REAL`, `ByteArray` becomes `BLOB`), and a non-null Kotlin type adds `NOT NULL`; - **every** property is persisted unless you exclude it with **`@Ignore`**, or list it in `ignoredColumns` when it comes from a parent class. So a recipe app's `Recipe` class with an id, a title and a preparation time is, to Room, a three-column `recipes` table. Editing the class edits that table. ## What Room needs from the class | Requirement | How you satisfy it | If it is missing | |---|---|---| | A primary key | `@PrimaryKey` on one property, or `@Entity(primaryKeys = [...])` for several columns | the build fails | | A way to build objects from rows | a constructor whose parameters match the persisted properties by name and type, or a no-arg constructor with settable properties | the build fails | | Access to each column | public properties, or non-private getters and setters | Room cannot read or write the column | | Defaults for ignored constructor parameters | a default value such as `= null` | Room cannot call the constructor | The last row follows from the second: Room calls the primary constructor when it turns a query result into an object, so an `@Ignore` parameter in that constructor needs a default for Room to leave it out. ## @Database: the table list and the schema version A Room database is an **abstract class that extends `RoomDatabase`** and carries **`@Database`**: - **`entities`** lists every entity class whose table belongs in this database. An `@Entity` class that is not listed gets no table here, and a DAO query that names its table fails at compile time. - **`version`** is the integer schema version, starting at 1. You raise it whenever the schema changes; how existing files get from one version to the next is the job of migrations, a separate lesson. - **`exportSchema`** (default `true`) asks Room to write the schema as JSON into a configured schema folder; when no folder is configured, Room prints a build warning. - An abstract function per `@Dao` type gives callers access to the queries. ## What happens at build time and on first open 1. The processor validates every entity: a primary key exists, and every column named by a key, an index or a foreign key exists. 2. It generates a `<Database>_Impl` class holding the `CREATE TABLE` and `CREATE INDEX` statements, plus the DAO implementations, checking each `@Query` against the declared tables. 3. When the database file is first created, that code creates the tables and Room's own bookkeeping table, `room_master_table`, which stores an **identity hash** of the compiled schema. 4. On every later open, Room compares the stored hash with the compiled one. If an entity changed but `version` did not, Room throws an `IllegalStateException` ("Room cannot verify the data integrity...") rather than read a table whose shape it no longer knows. ## Same annotations in both majors Room 2.x lives in the `androidx.room` package and Room 3.0 in `androidx.room3`. `@Entity`, `@PrimaryKey`, `@ColumnInfo`, `@Ignore`, `@Index`, `@ForeignKey` and `@Database` keep their names and meaning across the move, with a few properties added in 3.0, so an entity reads the same in both apart from its imports. ## Mistakes interviewers listen for - Treating `@Entity` as a serialization hint and expecting the whole object in one column. - Adding an entity class but forgetting to list it in `@Database(entities = [...])`. - Renaming a class or property without a pinned `tableName` or `@ColumnInfo(name = ...)`, which silently renames the table or column. - Changing an entity without raising `version`, which fails on users' devices at first open.

  • Why does an @Ignore property declared in a Room entity's primary constructor need a default value?
    Room builds entity objects from query results by calling the constructor whose parameters match the persisted columns. An ignored property has no column, so the generated code has nothing to pass for it; a default such as `= null` lets Room call the constructor without that argument. Declaring the ignored property in the class body avoids the question altogether.
  • What happens if you rename a Room entity class without setting tableName?
    The table name comes from the class name, so the rename changes the schema and the compiled identity hash. Without a version bump, existing installs fail on open with Room's data-integrity `IllegalStateException`; with one, you need a migration that renames the table. Pinning `tableName`, and column names with `@ColumnInfo(name = ...)`, keeps Kotlin refactors from becoming schema changes.

  • An @Entity is stored as one serialized blob, like a JSON document.
  • Room finds every @Entity class on the classpath without listing it in @Database.
  • Only properties annotated with @ColumnInfo become columns.
  • The @Database version is just documentation that Room never checks.
  • Room inspects entity classes by reflection at runtime to work out the schema.
open as a page

In Room, how do you declare a composite primary key and a unique index on an entity, and what does each one generate?

level: middleimportance: should knowfreq 45%

basics

~20 s

A composite key goes in @Entity(primaryKeys = [...]) and becomes a PRIMARY KEY(a, b) table constraint; a unique index goes in @Entity(indices = [Index(value = [...], unique = true)]) and becomes a separate CREATE UNIQUE INDEX statement.

open as a page

In Room, what does @ForeignKey with onDelete = CASCADE declare on a child entity, and why does Room warn about an unindexed child column?

level: middleimportance: should knowfreq 50%

basics

~20 s

@ForeignKey adds a FOREIGN KEY clause to the child table's CREATE TABLE, so SQLite deletes a recipe's ingredients when the recipe is deleted. Room warns about a missing child index because every parent delete or key change would scan the whole child table.

open as a page

In Room, what CREATE TABLE statement does an @Entity generate, and how do nullability, @PrimaryKey(autoGenerate) and @ColumnInfo shape it?

level: middleimportance: should knowfreq 50%

basics

~20 s

Room writes CREATE TABLE IF NOT EXISTS with one column per property: the Kotlin type picks the affinity, a non-null type adds NOT NULL, autoGenerate makes an INTEGER PRIMARY KEY AUTOINCREMENT, and @ColumnInfo sets the name, affinity, collation, index and DEFAULT.

open as a page

When an Android app moves from Room 2.x to Room 3.0, what changes in the Gradle setup and the database builder, and what does getSupportWrapper() bridge?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Room 3.0 moves to androidx.room3 artifacts and imports, runs only as a KSP processor that generates Kotlin, and opens databases through a SQLiteDriver instead of SupportSQLite; getSupportWrapper() from room3-sqlite-wrapper gives legacy code a SupportSQLiteDatabase over Room's connections.

open as a page

As the lead of a production Android app on Room 2.8, when would you move it to Room 3.0, and how would you stage the move?

level: principalimportance: should knowfreq 30%

basics

~20 s

Move when you need what only Room 3.0 brings, such as multiplatform targets or its new features, and can afford KSP-only builds and suspend DAOs. Stage it on 2.8 first, with setDriver, the SupportSQLite wrapper, KSP and suspend DAOs, then swap packages.

open as a page