Room Database: Entities, DAOs and Flow

Android Development 14 min min read Updated: Nov 16, 2026 Intermediate
Room Database: Entities, DAOs and Flow
Intermediate Topic 4 of 6

What is Room?

Room is Google's library that sits on top of SQLite. You write Kotlin classes and interface methods. Room checks your SQL at compile time and gives you results as Flows.

Setup

kotlin plugins { alias(libs.plugins.ksp) } dependencies { implementation(libs.androidx.room.runtime) implementation(libs.androidx.room.ktx) ksp(libs.androidx.room.compiler) }

1. Entity (a table)

kotlin @Entity(tableName = "notes") data class NoteEntity( @PrimaryKey(autoGenerate = true) val id: Int = 0, val title: String, val content: String, @ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis(), val pinned: Boolean = false )

2. DAO (queries)

kotlin @Dao interface NoteDao { @Query("SELECT * FROM notes ORDER BY pinned DESC, created_at DESC") fun observeAll(): Flow<List<NoteEntity>> // emits again whenever the table changes @Query("SELECT * FROM notes WHERE title LIKE '%' || :query || '%'") fun search(query: String): Flow<List<NoteEntity>> @Query("SELECT * FROM notes WHERE id = :id") suspend fun getById(id: Int): NoteEntity? @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(note: NoteEntity): Long @Update suspend fun update(note: NoteEntity) @Delete suspend fun delete(note: NoteEntity) }

3. Database

kotlin @Database(entities = [NoteEntity::class], version = 1, exportSchema = true) abstract class AppDatabase : RoomDatabase() { abstract fun noteDao(): NoteDao } val db = Room.databaseBuilder(context, AppDatabase::class.java, "app.db").build() // create ONE instance
Room runs queries off the main thread: suspend functions and Flow return types make Room run on a background thread for you. Never allow main-thread queries.

4. Repository and ViewModel

kotlin class NoteRepository(private val dao: NoteDao) { fun notes(query: String): Flow<List<NoteEntity>> = if (query.isBlank()) dao.observeAll() else dao.search(query) suspend fun save(note: NoteEntity) = dao.insert(note) suspend fun delete(note: NoteEntity) = dao.delete(note) } class NotesViewModel(private val repository: NoteRepository) : ViewModel() { val query = MutableStateFlow("") @OptIn(ExperimentalCoroutinesApi::class) val notes: StateFlow<List<NoteEntity>> = query .debounce(250) .flatMapLatest { repository.notes(it) } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) fun add(title: String, content: String) = viewModelScope.launch { repository.save(NoteEntity(title = title, content = content)) } fun delete(note: NoteEntity) = viewModelScope.launch { repository.delete(note) } }

5. Compose Screen

kotlin @Composable fun NotesScreen(viewModel: NotesViewModel) { val notes by viewModel.notes.collectAsStateWithLifecycle() val query by viewModel.query.collectAsStateWithLifecycle() Column { OutlinedTextField(query, { viewModel.query.value = it }, label = { Text("Search") }, modifier = Modifier.fillMaxWidth().padding(16.dp)) LazyColumn(contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { items(notes, key = { it.id }) { note -> Card(Modifier.fillMaxWidth()) { Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(note.title, style = MaterialTheme.typography.titleMedium) Text(note.content, maxLines = 2) } IconButton(onClick = { viewModel.delete(note) }) { Icon(Icons.Default.Delete, "Delete") } } } } } } }

Type Converters

kotlin class Converters { @TypeConverter fun fromTags(tags: List<String>): String = tags.joinToString(",") @TypeConverter fun toTags(value: String): List<String> = if (value.isEmpty()) emptyList() else value.split(",") } // @Database(...) @TypeConverters(Converters::class)
Tip: Use Database Inspector in Android Studio (View > Tool Windows > App Inspection) to look at your tables while the app runs.

Conclusion

Room gives you a type-safe local database. Entities define tables, DAOs define queries and Flow keeps your UI updated automatically.

Quick Summary: @Entity, @Dao, @Database, Flow queries and suspend writes. Wrap Room in a repository and expose the data from a ViewModel.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators