Room: entities, DAOs, queries
Why it matters
- Room's compiler (run through KSP) checks every
@Querystring against your entities at build time, so a typo in a column name fails the build instead of crashing at runtime. - Flow-returning DAO queries re-emit when a table they read is written, which removes manual refresh calls and stale-UI bugs.
- Interviewers probe transaction boundaries,
@Upsertversus@Insert(onConflict = REPLACE), how@Relationloads data, TypeConverter registration and how Flow invalidation really works. - The schema you define here (primary keys, indices, foreign keys) is the contract the migration lesson builds on.
The simple explanation
- An entity is the header row of a spreadsheet tab: it names the table and its columns.
- A DAO is the list of questions you are allowed to ask the spreadsheet, each written in SQL and checked before the app ships.
- A Flow query is a live dashboard: when anyone writes to a tab it reads from, the dashboard runs its query again.
- A transaction is a notary stamp: either every write in the block lands, or none do.
- @Upsert is a "save" button: the row is inserted if its key is new, updated if the key already exists.
Room is a persistence library on top of SQLite. Its annotation processor (room-compiler, run with KSP) reads your annotations at compile time and generates the DAO and database implementations, so there is no runtime reflection.
Entity layer. An @Entity data class becomes a table. @PrimaryKey marks the key column (autoGenerate = true lets SQLite assign it). Index speeds up WHERE, JOIN and ORDER BY on the listed columns. ForeignKey enforces referential integrity in SQLite (Room turns foreign-key enforcement on). @Embedded flattens the fields of a plain class (such as an Address) into the parent table's columns. @Relation loads related rows into a result class: Room runs the parent query, then a second query for the children, and stitches them together, which is why the DAO method should be @Transaction.
DAO layer. An @Dao interface declares the operations. Three return shapes matter:
| Return type | Behaviour |
|---|---|
suspend fun | Runs once off the main thread (Room moves the work itself) and returns one result. |
Flow<T> | Emits the current result, then re-runs the query and emits again after every write to a table it reads. |
List<T> or T (non-suspend) | Runs on the calling thread; Room throws if that is the main thread, unless allowMainThreadQueries() is set. |
Invalidation. Room's InvalidationTracker adds SQLite triggers to the tables your observable queries read. When a write transaction finishes, Room checks which tables changed and tells their observers, and each affected Flow runs its query again. The granularity is the table, not the row: a write to any row, even one your WHERE clause excludes, or one that leaves the data identical, causes a new emission. Add distinctUntilChanged() if that matters.
Writes. @Upsert tries an insert and, if the primary key already exists, updates that row instead. @Transaction on a DAO method, or database.withTransaction { } in a repository, makes several writes share one SQLite transaction: if anything throws, all of them roll back.
TypeConverters. Methods annotated with @TypeConverter tell Room how to store a type SQLite does not know (such as Instant) as a column type it does (Long). You register the class that holds them with @TypeConverters(...) on the database (or more narrowly on an entity, DAO or field). Enums need no converter: Room stores them by name.
Schema export. @Database(exportSchema = true) is the default. With a schema directory configured (the Room Gradle plugin's schemaDirectory), Room writes one JSON file per database version. Commit these files: auto-migrations and MigrationTestHelper read them.
Notes
- Setup: apply the KSP and
androidx.roomGradle plugins, addimplementation("androidx.room:room-runtime")andksp("androidx.room:room-compiler"), and setroom { schemaDirectory("$projectDir/schemas") }. The coroutine APIs, such aswithTransaction, now live inroom-runtime; the oldroom-ktxartifact is empty. @PrimaryKey val id: LongwithoutautoGeneratemeans you supply the id, which is what you want for server ids. UseautoGenerate = trueonly for ids created locally, and give the field a default of0so Room knows it is unset.- A Flow query re-emits after any write to a table it reads, not just to the rows it returns. Narrowing the
WHEREclause does not change that;distinctUntilChanged()drops repeated identical results. - Suspend DAO functions and Flow queries are main-safe, so a repository calls them without
withContext(Dispatchers.IO). Flow results arrive in the collector's context. - Prefer
@Upsertto@Insert(onConflict = OnConflictStrategy.REPLACE)when syncing. REPLACE deletes the conflicting row and inserts a new one, soON DELETE CASCADEforeign keys delete that row's children. Upsert updates the row in place. @Insert(onConflict = OnConflictStrategy.IGNORE)is the choice when an existing row must win, for example to keep a local edit.- Use
@Transaction(on a DAO method) ordb.withTransaction { }for multi-step writes. Without one, each call commits on its own, and a crash between them leaves half the change on disk. - Register converters with
@TypeConverters(Converters::class)on the@Databaseclass. A column type Room cannot store is a compile error ("Cannot figure out how to save this field"), not a runtime crash. - Mark
@Relationqueries@Transaction. Room runs more than one query for them; without the transaction a write can land between the parent and child queries, and Room warns at compile time. @RawQueryskips compile-time checking. Use it only for genuinely dynamic queries, and pass user input as bind arguments, never by string concatenation.
Code example
This shows two entities with a foreign key, an index, an embedded class and a TypeConverter, a DAO with Flow, suspend, @Upsert and a @Relation query, the database class, and a repository that writes two tables in one transaction.
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Delete
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Relation
import androidx.room.RoomDatabase
import androidx.room.Transaction
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import androidx.room.Upsert
import androidx.room.withTransaction
import java.time.Instant
import kotlinx.coroutines.flow.Flow
data class Address(val city: String, val country: String)
@Entity(tableName = "authors")
data class Author(
@PrimaryKey val id: Long, // server id, so no autoGenerate
val name: String,
@Embedded val address: Address, // becomes columns city and country
)
@Entity(
tableName = "articles",
indices = [Index(value = ["authorId", "publishedAt"])],
foreignKeys = [ForeignKey(
entity = Author::class,
parentColumns = ["id"],
childColumns = ["authorId"],
onDelete = ForeignKey.CASCADE,
)],
)
data class Article(
@PrimaryKey val id: Long,
val title: String,
val authorId: Long,
val publishedAt: Instant, // stored as Long by the converter below
)
// Result class for a @Relation query; not a table
data class AuthorWithArticles(
@Embedded val author: Author,
@Relation(parentColumn = "id", entityColumn = "authorId")
val articles: List<Article>,
)
class Converters {
@TypeConverter
fun toInstant(millis: Long?): Instant? = millis?.let(Instant::ofEpochMilli)
@TypeConverter
fun fromInstant(instant: Instant?): Long? = instant?.toEpochMilli()
}
@Dao
interface ArticleDao {
// Re-runs after any write to the articles table
@Query("SELECT * FROM articles WHERE authorId = :authorId ORDER BY publishedAt DESC")
fun observeByAuthor(authorId: Long): Flow<List<Article>>
@Upsert
suspend fun upsert(article: Article)
@Delete
suspend fun delete(article: Article)
@Query("DELETE FROM articles WHERE publishedAt < :cutoff")
suspend fun deleteOlderThan(cutoff: Instant): Int
}
@Dao
interface AuthorDao {
@Upsert
suspend fun upsert(author: Author)
// Two queries under the hood (authors, then articles), so wrap them in one transaction
@Transaction
@Query("SELECT * FROM authors WHERE id = :authorId")
fun observeWithArticles(authorId: Long): Flow<AuthorWithArticles?>
}
@Database(entities = [Author::class, Article::class], version = 1, exportSchema = true)
@TypeConverters(Converters::class)
abstract class AppDb : RoomDatabase() {
abstract fun articles(): ArticleDao
abstract fun authors(): AuthorDao
}
class PublishRepository(private val db: AppDb) {
// Both rows commit together or not at all. No withContext: Room DAO calls are main-safe.
suspend fun publish(author: Author, article: Article) {
db.withTransaction {
db.authors().upsert(author)
db.articles().upsert(article)
}
}
}- The composite index starts with
authorId, so it serves both theobserveByAuthorquery and the foreign-key lookups Room would otherwise warn about. AuthorWithArticlesis not a table. Room fillsarticleswith a second query, and@Transactionkeeps the two reads consistent.java.time.Instantneeds API 26, or core library desugaring on older devices.withTransactionis the repository-level way to group writes from several DAOs; a@Transactionmethod does the same inside one DAO.
Run the idea in plain Kotlin
A MutableStateFlow map stands in for a table, and every write produces a new value, like Room's table-level invalidation. One observer sees every emission; the other uses distinctUntilChanged() and skips the write that changed nothing it shows.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
data class Article(val id: Long, val authorId: Long, val title: String)
class FakeArticleTable {
private val rows = MutableStateFlow(mapOf<Long, Article>())
// Like @Upsert: insert a new key, update an existing one
fun upsert(article: Article) {
val existed = rows.value.containsKey(article.id)
// A new table value: like Room, every observer of the table re-runs its query
rows.value = rows.value + (article.id to article)
println((if (existed) "updated " else "inserted ") + article.id)
}
fun observeByAuthor(authorId: Long): Flow<List<String>> =
rows.map { table -> table.values.filter { it.authorId == authorId }.sortedBy { it.id }.map { it.title } }
}
fun main() = runBlocking {
val table = FakeArticleTable()
val raw = launch { table.observeByAuthor(1).collect { println("raw " + it) } }
val distinct = launch { table.observeByAuthor(1).distinctUntilChanged().collect { println("distinct " + it) } }
yield()
table.upsert(Article(1, authorId = 1, title = "Room basics")); yield()
table.upsert(Article(2, authorId = 2, title = "Other author")); yield()
table.upsert(Article(1, authorId = 1, title = "Room in depth")); yield()
raw.cancel()
distinct.cancel()
}Expected output:
raw []
distinct []
inserted 1
raw [Room basics]
distinct [Room basics]
inserted 2
raw [Room basics]
updated 1
raw [Room in depth]
distinct [Room in depth]
In production
- Users reported that the article list did not update after a background sync wrote new rows.
- The DAO exposed
suspend fun getAll(): List<Article>, and the ViewModel called it once ininit. - No crash and no error: the screen kept showing the snapshot from when it opened.
- Changed the DAO to
fun observeAll(): Flow<List<Article>>and turned it into UI state withstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()). - Added a DAO test against
Room.inMemoryDatabaseBuilderthat collects the Flow, upserts a row and asserts a second emission. - Audited the other DAOs for one-shot reads behind screens that should stay live.
- Support saw orders that showed a total but an empty item list.
- Checkout called
orderDao.upsert(order)and thenitemDao.upsertAll(items)as two separate suspend calls, each committing on its own. - When the process died between the two calls (low memory, user swiping the app away), the order row survived without its items.
- Wrapped both writes in
db.withTransaction { }in the repository, so the order and its items commit together or not at all. - Added an in-memory database test where the item DAO throws after the order is written, and asserted that the order row was rolled back.
- Added a one-time cleanup in the next migration that deletes orders with no items.
Common mistakes
- Using @Insert(onConflict = REPLACE) to sync rows that have children. REPLACE deletes the old row before inserting the new one, so
ON DELETE CASCADEchildren disappear.@Upsertupdates the existing row in place and the children stay. - Not configuring a schema directory, or not committing the JSON files.
exportSchemais on by default, but without a directory nothing is written, and without the files in version control auto-migrations andMigrationTestHelperhave nothing to compare against. - Returning a one-shot List for a screen that should stay current. It is a snapshot. Rows written later by a sync or another screen never appear. Return
Flowso Room re-runs the query after each write. - Expecting a narrow WHERE clause to limit Flow emissions. Room invalidates whole tables. A query for one author re-emits when any article is written. Use
distinctUntilChanged(), and split very hot tables if needed. - Writing related rows without a transaction. Each DAO call commits on its own, so a crash between calls leaves partial data. Use
@TransactionorwithTransaction. - Building a @RawQuery from user input by concatenating strings. That skips compile-time checking and opens a SQL-injection path. Pass the values as bind arguments.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What happens when a DAO method returns a Flow?”
“What is @Upsert and when would you choose it over @Insert?”
“How does Room handle types that SQLite does not support natively?”
“How do you make several writes atomic in Room?”
Quiz
A DAO query reads articles WHERE authorId = 1 and returns a Flow. Another screen updates an article with authorId = 2. What happens?
What is the main difference between @Upsert and @Insert(onConflict = OnConflictStrategy.REPLACE)?
Where do you register a class that holds @TypeConverter methods so the whole database can use it?
A repository calls orderDao.upsert(order), then itemDao.upsertAll(items), with no transaction. The process dies between the calls. What is on disk?
0 of 4 answered
Mini task
- Apply the KSP and
androidx.roomplugins, addroom-runtimeandksp("androidx.room:room-compiler"), and setroom { schemaDirectory("$projectDir/schemas") }. - Create an
@Entitydata classNotewith@PrimaryKey(autoGenerate = true) val id: Long = 0,val text: Stringandval createdAt: Long, with an index oncreatedAt. - Create an
@DaointerfaceNoteDaowith:fun observeAll(): Flow<List<Note>>ordered bycreatedAtdescending,@Upsert suspend fun upsert(note: Note),@Query("DELETE FROM Note WHERE createdAt < :cutoff") suspend fun deleteOlderThan(cutoff: Long): Int.
- Create the
@Databaseclass withversion = 1that exposesNoteDao. - In a
ViewModel, exposenoteDao.observeAll().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()), and collect it in the screen withcollectAsStateWithLifecycle(). - Add a button that calls
upsertwith a newNotefromviewModelScope.launch, withoutwithContext.
Done condition: the app builds with KSP, the list updates right after the upsert without any manual reload, and schemas/.../1.json exists in your module.