Persistence Layer

Personal Catalogue: Android (Kotlin & Compose)

Course 1 ยท Chapter 3 ยท DAOs, Database, Repository and Hilt

Chapter 2 described the data; this chapter makes it real. You will add Room to the project, write the DAOs (the interfaces that hold your queries), build the database class, seed the four item types, put a repository in front of it all, and wire the pieces together with Hilt. By the end the app can store and load a catalogue, though nothing on screen uses it until Chapter 4.

What was run, and what was not, and a version warning
Nothing here was compiled or run; there is no Android Studio on this machine. More importantly, my search found that Room now has two generations. Room 2.x (the androidx.room packages, which Chapter 2 and this chapter use) and the newer Room 3.0, whose packages are androidx.room3, which requires KSP and changes some APIs. A new project today might be offered either. This course is written against Room 2.x; if you choose Room 3, the ideas are the same but every androidx.room import, the artifact names and some signatures change, and you should follow Google's migration page (linked at the end).

Where This Layer Sits

LayerAndroid classWeb catalogue equivalent
TablesEntities (Chapter 2)Django models
QueriesDAO interfacesORM queries, Item.objects.filter()
ConnectionRoomDatabase subclassThe database connection and settings
Business rulesRepository classA service or model-manager layer
WiringHilt modulesDependency setup in the framework (settings.py, app factory)

The spec's rule is one repository class between the UI and the database. Screens (Chapter 4 onward) will talk only to the repository, never to a DAO, which keeps the rules in one place and makes the view models testable in Chapter 10.

Adding Dependencies

Room needs a runtime library, an annotation processor, and (per Google's setup page) KSP to run that processor. room-ktx adds coroutine support, including the withTransaction function used below. Hilt needs its own plugin, runtime and compiler, plus a Compose-aware helper for view models. Add them through the version catalog you met in Chapter 1. The version numbers are placeholders: copy the current ones from the release pages, and make the KSP version match your Kotlin version, as KSP releases are tied to Kotlin releases.

# gradle/libs.versions.toml [versions] room = "x.y.z" # Room 2.x line; see the Room release page hilt = "x.y.z" ksp = "x.y.z-x.y.z" # must match your Kotlin version hiltNavigationCompose = "x.y.z" [libraries] androidx-room-runtime = { module = "androidx.room:room-runtime", version.ref = "room" } androidx-room-ktx = { module = "androidx.room:room-ktx", version.ref = "room" } androidx-room-compiler = { module = "androidx.room:room-compiler", version.ref = "room" } hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hilt" } hilt-compiler = { module = "com.google.dagger:hilt-android-compiler", version.ref = "hilt" } androidx-hilt-navigation-compose = { module = "androidx.hilt:hilt-navigation-compose", version.ref = "hiltNavigationCompose" } [plugins] ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }
// app/build.gradle.kts (add inside the existing blocks) plugins { // ...the generated plugins stay... alias(libs.plugins.ksp) alias(libs.plugins.hilt) } dependencies { // ...the generated dependencies stay... implementation(libs.androidx.room.runtime) implementation(libs.androidx.room.ktx) ksp(libs.androidx.room.compiler) implementation(libs.hilt.android) ksp(libs.hilt.compiler) implementation(libs.androidx.hilt.navigation.compose) }

The two plugins must also be declared (with apply false) in the project-level build.gradle.kts, the same way the wizard declared the others. Then use File > Sync Project with Gradle Files. The red underlines in Chapter 2's files should vanish; if one remains, read the sync error first.

The DAOs

A DAO (data access object) is an interface whose methods carry SQL or an annotation such as @Insert. Room writes the implementation for you at build time. Methods that read return a Flow, which re-emits whenever the underlying tables change; that is what will keep the list screen up to date with no manual refreshing. Methods that write are suspend functions, so they run off the main thread.

package com.example.catalogue.data import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import kotlinx.coroutines.flow.Flow @Dao interface ItemTypeDao { @Query("SELECT * FROM item_type ORDER BY id") fun observeAll(): Flow<List<ItemType>> @Query("SELECT COUNT(*) FROM item_type") suspend fun count(): Int @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertAll(types: List<ItemType>) } @Dao interface TagDao { @Query("SELECT * FROM tag ORDER BY name") fun observeAll(): Flow<List<Tag>> @Query("SELECT * FROM tag WHERE name = :name LIMIT 1") suspend fun findByName(name: String): Tag? // Returns the new row id, or -1 if the name already exists (ignored by the unique index). @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(tag: Tag): Long } @Dao interface ItemDao { @Transaction @Query("SELECT * FROM item ORDER BY createdAt DESC") fun observeAll(): Flow<List<ItemWithDetails>> @Transaction @Query("SELECT * FROM item WHERE id = :id") fun observeById(id: Long): Flow<ItemWithDetails?> @Insert suspend fun insert(item: Item): Long @Update suspend fun update(item: Item) @Delete suspend fun delete(item: Item) } @Dao interface ItemTagDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertAll(refs: List<ItemTagCrossRef>) @Query("DELETE FROM item_tag WHERE itemId = :itemId") suspend fun deleteForItem(itemId: Long) }

Put them in ItemDao.kt, TagDao.kt, ItemTypeDao.kt and ItemTagDao.kt (Kotlin allows several per file, but one per file is easier to find). Notice @Transaction on the two methods that return ItemWithDetails: as Chapter 2 said, Room runs several queries to fill the type and tags, and the annotation makes them one consistent read. Notice also that findByName compares name = :name with no case handling: because the Tag.name column was declared NOCASE in Chapter 2, SQLite should apply that collation to the comparison, so a search for "SCI-FI" finds "sci-fi".

The Database Class

The database class lists every entity, declares a version, and exposes the DAOs. It is abstract: Room generates the concrete class.

package com.example.catalogue.data import androidx.room.Database import androidx.room.RoomDatabase @Database( entities = [ItemType::class, Item::class, Tag::class, ItemTagCrossRef::class], version = 1, exportSchema = true ) abstract class AppDatabase : RoomDatabase() { abstract fun itemTypeDao(): ItemTypeDao abstract fun tagDao(): TagDao abstract fun itemDao(): ItemDao abstract fun itemTagDao(): ItemTagDao }

version = 1 matters later: when you change an entity after the app is installed, you raise the version and supply a migration. While developing, uninstalling the app from the emulator is an easy way to start from a clean database. exportSchema = true asks Room to write a JSON description of each version, which migrations and tests use; Room may warn at build time if you have not told it where to write the files (a room.schemaLocation setting in the KSP configuration), so set one if it does.

Hilt Wiring

Something must build the one database and hand it to whoever needs it. You could write a hand-made singleton, but this course follows Android Development: Architecture & Data and uses Hilt, lightly: three small pieces.

// CatalogueApplication.kt (package com.example.catalogue) import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class CatalogueApplication : Application() // MainActivity.kt: add one annotation above the existing class line import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { /* unchanged */ } // data/DatabaseModule.kt package com.example.catalogue.data import android.content.Context import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun provideDatabase(@ApplicationContext context: Context): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "catalogue.db").build() @Provides fun provideItemTypeDao(db: AppDatabase): ItemTypeDao = db.itemTypeDao() @Provides fun provideTagDao(db: AppDatabase): TagDao = db.tagDao() @Provides fun provideItemDao(db: AppDatabase): ItemDao = db.itemDao() @Provides fun provideItemTagDao(db: AppDatabase): ItemTagDao = db.itemTagDao() }

Register the application class in AndroidManifest.xml by adding android:name=".CatalogueApplication" to the <application> tag. Without that line Hilt never starts and the build or first launch fails with a Hilt error. @Singleton on provideDatabase is essential: opening several instances of one database file is a bug.

The Repository

The repository holds the logic that is more than a single query: saving an item and its tag links as one unit, and making sure the four item types exist. @Inject constructor lets Hilt build it, and @Singleton keeps one copy.

package com.example.catalogue.data import androidx.room.withTransaction import kotlinx.coroutines.flow.Flow import javax.inject.Inject import javax.inject.Singleton @Singleton class CatalogueRepository @Inject constructor( private val db: AppDatabase, private val itemTypeDao: ItemTypeDao, private val tagDao: TagDao, private val itemDao: ItemDao, private val itemTagDao: ItemTagDao ) { val itemTypes: Flow<List<ItemType>> = itemTypeDao.observeAll() val tags: Flow<List<Tag>> = tagDao.observeAll() val items: Flow<List<ItemWithDetails>> = itemDao.observeAll() fun observeItem(id: Long): Flow<ItemWithDetails?> = itemDao.observeById(id) /** Call once at startup. Safe to call every launch: it only inserts when the table is empty. */ suspend fun ensureSeeded() { if (itemTypeDao.count() == 0) { itemTypeDao.insertAll( listOf("Book", "CD", "DVD", "Blu-ray").map { ItemType(name = it) } ) } } /** Saves a new item (id == 0) or updates an existing one, and replaces its tag links, atomically. */ suspend fun saveItem(item: Item, tagIds: Set<Long>): Long = db.withTransaction { val id = if (item.id == 0L) { itemDao.insert(item) } else { itemDao.update(item) item.id } itemTagDao.deleteForItem(id) itemTagDao.insertAll(tagIds.map { ItemTagCrossRef(itemId = id, tagId = it) }) id } suspend fun deleteItem(item: Item) = itemDao.delete(item) /** Returns the existing tag with this name (any case), or creates it. */ suspend fun getOrCreateTag(rawName: String): Tag { val name = rawName.trim() tagDao.findByName(name)?.let { return it } val newId = tagDao.insert(Tag(name = name)) return Tag(id = newId, name = name) } }

The seeding function is called from the activity or a view model in Chapter 4: ensureSeeded() checks the count and inserts only when the table is empty, so it is safe on every launch. A RoomDatabase.Callback.onCreate is the other common place to seed, but its method signature differs between Room versions (the older SupportSQLiteDatabase, the newer SQLiteConnection, and suspend functions in Room 3), whereas this repository approach does not depend on any of them.

A subtle point in getOrCreateTag: if two tags are created at once, the second insert returns -1 because of the unique index, and the code above would then return a tag with a wrong id. Chapter 7 tightens this by re-reading the tag after an ignored insert; for now the form creates tags one at a time, so it cannot happen.

Compare with the iOS course
In Personal Catalogue: iOS (Swift & SwiftUI) Chapter 3 the same layer is smaller: SwiftData's ModelContainer replaces the database class and the DAOs, queries come from @Query in the views, and no dependency-injection library is needed. The repository still exists to hold "save with tags" and the seeding. Android pays for flexibility with more setup; SwiftUI pays for brevity with less control over where queries live.

Challenges

Exercise 1

Add the dependencies and plugins, create CatalogueApplication, annotate MainActivity, register the application in the manifest, and add the database class, DAOs, module and repository. Build the project. List every error you got and which of the setup steps each pointed to.

๐Ÿ“„ View solution
Exercise 2

Add a DAO query that returns how many items have a given tag id, as a Flow<Int>, and expose it from the repository. Say which index from Chapter 2 makes it quick.

๐Ÿ“„ View solution
Exercise 3

Without writing code, explain what happens if saveItem is written without db.withTransaction and the app is killed between the item insert and the tag insert. Then explain why that cannot leave an orphan row when the transaction is used.

๐Ÿ“„ View solution

Chapter 3 Quick Reference

  • Room needs room-runtime, room-ktx and the compiler through ksp; Hilt needs its plugin, hilt-android and its compiler through ksp. This course uses Room 2.x (androidx.room); Room 3 uses androidx.room3
  • DAO: @Dao interface; reads return Flow, writes are suspend; @Transaction on queries returning relation classes
  • Database: @Database(entities, version, exportSchema) on an abstract RoomDatabase with one abstract function per DAO
  • Hilt: @HiltAndroidApp on the Application (registered in the manifest), @AndroidEntryPoint on the activity, @Module @InstallIn(SingletonComponent) with @Provides @Singleton
  • Repository: @Singleton class ... @Inject constructor; the only thing screens talk to
  • Seeding: ensureSeeded() inserts the four types when the table is empty
  • Multi-step writes go inside db.withTransaction { }
Not Yet Verified
Checked (one web search on 2026-11-19): that Room 2.x uses room-runtime, room-compiler through ksp and optionally room-ktx; that Room 3.0 exists with androidx.room3 packages, requires KSP and has different callback signatures; that the (deprecated) Hilt codelab provides the database from a SingletonComponent module with @Singleton, and the DAO from a second @Provides function.
Not checked, from general knowledge: every artifact name outside Room (hilt-android, hilt-android-compiler, hilt-navigation-compose, the plugin ids); that Room 2.8 still ships room-ktx with withTransaction; the NOCASE comparison in findByName; exportSchema and room.schemaLocation behaviour; the Gradle layout for plugins; and all code, none of which was compiled. Version numbers are deliberately left as placeholders because I could not confirm a compatible Room, Hilt, KSP and Kotlin set.
Sources for This Chapter
Search results (2026-11-19): Android Developers, Room release notes; Save data in a local database using Room; Migrate from Room 2.x to Room 3.0; (Deprecated) Using Hilt in your Android app. Only titles and short summaries in the search results were used.
Coming next
Personal Catalogue: Android (Kotlin & Compose) 4 builds the list screen: a view model that exposes the repository's Flow as StateFlow, a LazyColumn of items, type filter chips and an empty state.