HomeTutorialsRoom Database in Kotlin

Room Database in Kotlin

What is Room?

Room is part of the Android Architecture Components presented in the Google I/O 2016. It is not an ORM, it is a whole library that allows us to create and manipulate SQLite databases easier, by using annotations we can define our databases, its tables, and operations.

Room will automatically translate these annotations into SQLite instructions/queries to perform the correspondent operations into the DB engine.

Room architecture looks like follow:

1 jT94pc71uD A2TPN E2ulg
Room Database in Kotlin 2

The three major components of Room are:

  • Database: It represents the DB, it is an object that holds a connection to the SQLite DB and all the operations are executed through it. It is annotated with @Database.
  • 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 .

Here is an example Room Database in Kotlin

STEP – 1 Add Dependency in app level buid.gradle file

dependencies {
  def room_version = "2.2.5"

  implementation "androidx.room:room-runtime:$room_version"
  kapt "androidx.room:room-compiler:$room_version" // For Kotlin use kapt 


Also we need to add plugin in build.gradle file

apply plugin: 'kotlin-kapt'

Now we want to create a table in which we can store users so we have to do following steps

STEP- 2 Create a kotlin data class

data class User(
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "first_name") val firstName: String?,
    @ColumnInfo(name = "last_name") val lastName: String?

Already mentioned entity is a table in Room database so we want to create a table with table name User (table name will be same as data class name) and will have 3 fields- uid (which will be Primary key), first_name and last_name.

STEP – 3 Create an interface in kotlin

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)

@Dao represent the database methods to be used, we use @Insert for inserting data, @delete for deleting data, and @Query to query data.

STEP – 4 Create a database

@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

STEP – 5 Call this database in your MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

       val db = Room.databaseBuilder(
            AppDatabase::class.java, "database-name"
        ).build()  // 1
       db.userDao().insertAll(User(1, "Jayant", "Dhingra")) // 2


Understanding MainActivity

Part 1 => We are creating a Room database builder class then passing the application context , databse class and database name.

Part 2 => We are calling insertAll method from user Dao.

Thats all Folks!!

Jayant dhingra
Jayant dhingrahttps://apps.shopify.com/incredible-countdown-timer
As an enthusiast of stock markets and a skilled developer specializing in Android and augmented reality technologies, I am constantly driven to experiment with code. Additionally, I am a co-founder of Incredible Apps, a company committed to creating exceptional mobile experiences. For those using Shopify, be sure to check out our latest app, Incredible Countdown Timer, available for installation at https://apps.shopify.com/incredible-countdown-timer.

Related Articles

Popular Post