Contents
CWCoding With DhrumilCW Practical Flutter and Kotlin tutorials for working mobile developers

Home › Articles

Room Database in Kotlin: Entities, DAOs and Migrations

By Priya Shah · Published · 4 min read

Filing cabinet with labeled drawers representing local database storage.
Filing cabinet with labeled drawers representing local database storage. · Foto: DreamQuest / Pixabay

Room is the abstraction layer most Kotlin Android apps eventually reach for once a key-value store stops being enough. It wraps SQLite, validates your SQL at compile time, and gives you suspend-friendly DAOs, but it also introduces a schema contract you have to maintain for the life of the app.

This guide walks through the pieces you actually write: entities that map to tables, DAOs that hold queries, a database class that wires them together, and the migration habits that keep existing installs from crashing after an update.

Entities Define the Contract

An entity is a Kotlin data class annotated with @Entity. Give it a primary key with @PrimaryKey(autoGenerate = true) for surrogate IDs or assign your own when the ID comes from a server. Column names default to property names, so rename with @ColumnInfo when the SQL naming convention differs from the Kotlin one.

Indices matter more than beginners expect. A @Index on a foreign key column or any column you filter by keeps lookups fast; without it, a query against 50,000 rows can go from a few milliseconds to a few hundred. Add unique indices where duplicates would corrupt your logic, such as an external ID or a normalised email.

Relationships use @Relation with @Transaction on the DAO method, or plain foreign keys with onDelete = CASCADE. Prefer explicit join queries when the relation is deep, since Room's relation loading issues one query per parent by default and can snowball on large result sets.

  • @PrimaryKey(autoGenerate = true) for local IDs, plain @PrimaryKey for server IDs
  • @ColumnInfo to map snake_case SQL to camelCase Kotlin
  • @Index on every column used in WHERE or ORDER BY
  • @Embedded for flat value objects you do not want as separate tables
1800One-by-one220Batched x10090Single transaction60Transaction + prep
Relative time for 1,000 inserts (ms)

DAOs: Where Queries Live

A DAO is an interface annotated with @Dao. Mark reads as suspend functions so Room moves them off the main thread, or return Flow<List<Item>> to observe changes automatically. Writes go in suspend functions or @Transaction blocks when several statements must succeed together.

Use @Insert(onConflict = OnConflictStrategy.REPLACE) for upserts, but be aware REPLACE deletes and reinserts the row, which fires foreign key cascades and resets auto-increment IDs. For partial updates, @Query with an explicit UPDATE statement is safer and cheaper than reading the entity, mutating it, and writing it back.

Keep DAOs narrow. One DAO per aggregate root, roughly 8 to 15 methods, is a comfortable size. When a DAO grows past 30 methods, split it by feature or read versus write, the same discipline that keeps other Android components manageable, as covered in sizing a RecyclerView adapter for smooth lists.

Database Class and Type Converters

The database class extends RoomDatabase, lists every entity in @Database(entities = [...], version = 1), and exposes abstract DAO getters. Build it once with Room.databaseBuilder and keep it as a singleton, typically created lazily in a DI module or an Application-scoped holder. Creating a second instance is the most common cause of mysterious lock contention.

Non-primitive fields need a @TypeConverter. Dates store well as Long epoch millis, enums as their name string, and lists as JSON through a converter. Converters apply database-wide, so define them once and register them with @TypeConverters on the database class rather than scattering them across entities.

  • Use Room.databaseBuilder(context, AppDatabase::class.java, "app.db")
  • Call .fallbackToDestructiveMigration() only in debug builds
  • Store dates as Long, not as formatted strings
  • Wrap converters in a single object and register globally

Migrations and Versioning

Every schema change bumps the version and ships a Migration. Adding a nullable column is a one-line ALTER TABLE; renaming or dropping requires a table copy, which on a 100,000-row table can take a few hundred milliseconds on mid-range hardware. Run migrations inside the builder, not after the database opens.

Room validates the schema hash at open time. If the migration produces a schema that does not match the entity definitions, the app throws IllegalStateException on first access, usually in production rather than in your tests. Export the schema to JSON with the room.schemaLocation annotation processor argument and keep those files in version control so you can diff changes.

Write a migration test for each version step using an in-memory database and the exported schema. It costs a few minutes per version and catches the failure mode that is hardest to reproduce in the field.

Threading and Performance Habits

Room's suspend support is convenient but not magic. A query returning 20,000 entities and mapping them to UI models will take noticeable time regardless of which thread runs it. Paginate with LIMIT and OFFSET, or return PagingSource for large lists, and keep row payloads small by selecting only the columns you display.

Transactions are cheap when short and expensive when long. Batch 500 to 1,000 inserts inside a single @Transaction rather than looping one insert at a time; the difference is often ten to twenty times faster. Avoid network calls inside a transaction, since the database lock will be held for the duration.

If your screens rebuild heavily on data changes, check how many composables or views each emission touches. Data flow and UI structure interact more than most people assume, as discussed in how many widgets a typical screen really uses.

Testing and Debugging

Room ships an in-memory builder for tests: Room.inMemoryDatabaseBuilder with allowMainThreadQueries in test scope. Test DAO behaviour against real SQLite rather than a mock, because the bugs you care about are query bugs, not interface bugs. Each test gets a fresh database, so ordering issues surface immediately.

For debugging, enable the query callback in debug builds to log statements and timings. Watch for missing indices by scanning for queries above roughly 16 ms on the main-thread-adjacent paths, and use EXPLAIN QUERY PLAN when a query looks suspicious. Small habits here prevent the slow list scroll that users notice first.

When Room Is the Wrong Tool

Room is a poor fit for small preference-like data, which belongs in DataStore, and for large blobs, which belong on the filesystem with a path stored in the database. It is also overkill for a cache of a single API response that you replace wholesale; a file cache is simpler and faster.

Pick Room when you need queries, joins, partial updates, and a schema you control. If you are still deciding between storage layers, the trade-offs mirror those in what a Flutter app costs to build: the cheap option is rarely the cheap option six months later.

Typical Room costs on a mid-range Android device
OperationDataset sizeTypical timeNote
Single indexed lookup1 rowunder 1 msIndex required
Full table scan50,000 rows20–80 msIndex the filter column
Batch insert in transaction1,000 rows40–120 msAvoid per-row inserts
Add nullable column100,000 rows10–50 msSimple ALTER TABLE
Table copy migration100,000 rows200–600 msRename or drop column
Open with schema validationany5–20 msRuns on first access
  • Index every column you filter or sort by; it is the single biggest query win.
  • Batch writes in transactions of 500–1,000 rows instead of inserting in a loop.
  • Export and version-control the schema JSON so migrations are testable.
  • Keep the database a singleton and never call destructive migration in release builds.
Priya Shah · Android and Kotlin author
Covers Kotlin, Jetpack libraries and Android architecture with a hands-on approach. Focuses on migration guides, database work and networking patterns for small teams.

Related articles

↑