Introduction to RoomDb

  • Entity: Represents a table within the Room Database. It should be annotated with @Entity.
  • DAO: An interface that contains the methods to access the Database. It is annotated with @Dao.
dependencies {
def room_version = "2.2.5"
implementation "$room_version"
kapt "$room_version" // For Kotlin use kapt
apply plugin: 'kotlin-kapt'
data class User(
@PrimaryKey val uid: Int,
@ColumnInfo(name = "first_name") val firstName: String?,
@ColumnInfo(name = "last_name") val lastName: String?
interface UserDao {
@Query("SELECT * FROM user")
fun getAll(): List<User>
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List<User>
@Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
fun findByName(first: String, last: String): User
fun insertAll(vararg users: User)
fun delete(user: User)
@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {
val db = Room.databaseBuilder(
applicationContext,, "database-name"
).build() // 1

db.userDao().insertAll(User(1, "Jayant", "Dhingra")) // 2



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store