Kotlin

Room — Android Database

admin by @admin ADMIN
1d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Room is the official Android persistence library — annotation-driven, compile-time SQL verification, coroutine + Flow integration out of the box.
Kotlin
Raw
// build.gradle.kts:
//   implementation("androidx.room:room-runtime:2.6.+")
//   ksp           ("androidx.room:room-compiler:2.6.+")
//   implementation("androidx.room:room-ktx:2.6.+")

import androidx.room.*
import kotlinx.coroutines.flow.Flow

@Entity(tableName = "users")
data class UserEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val name: String,
    val email: String,
    @ColumnInfo(name = "created_at") val createdAt: Long,
)

@Dao
interface UserDao {
    @Query("SELECT * FROM users ORDER BY created_at DESC")
    fun observeAll(): Flow<List<UserEntity>>        // reactive — emits on changes

    @Query("SELECT * FROM users WHERE id = :id")
    suspend fun findById(id: Long): UserEntity?

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(user: UserEntity): Long

    @Query("DELETE FROM users WHERE id = :id")
    suspend fun deleteById(id: Long)
}

@Database(entities = [UserEntity::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.