Room Database with Kotlin

Room is a persistence library, part of the Android Jetpack.
The Room is now considered as a better approach for data storing than SQLiteDatabase.
The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.

Why Room?

  • Compile-time verification of SQL queries.
  • You need to use lots of boilerplate code to convert between SQL queries and Java/Kotlin data objects. But, Room maps our database objects to Java Object without boilerplate code.
  • Room is built to work with Live data and RxJava

Room has 3 main components

  1. Entity: Represents table within the database. We can create a table in room database using @Entity annotation
  2. Dao: Contains all the methods used for accessing data from the database.
  3. Database: Contains the database holder and serves as the main access point for the underlying connection to your app’s persisted, relational data.

Implementation

To add Room database add the below lines into your app-level build.gradle file

implementation "androidx.room:room-runtime:2.2.4"
kapt "androidx.room:room-compiler:2.2.4"
implementation "androidx.room:room-ktx:2.2.4"

Don’t forget to add apply plugin: ‘kotlin-kapt’ in top your app-level build.gradle file

Creating Model Class

Room creates a table for each model class annotated with @Entity, the fields in the class correspond to a column in the table. Therefore each entity class tends to be a small model class contains no logic.

We are going to create a small class User represents a model for the data in the database.

Create a model class as shown below.

package com.kotlincodes.roomdatabasekotlin.model

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "users")
data class UserModel (
    @PrimaryKey(autoGenerate = true)
    var id:Int,
    var name:String,
    var mobile:String,
    var age:Int
)

Creating DAOs (Data Access Object)

DAOs contain all methods that are used to access data from database.

To create a DAO we need to create an interface annotated with @Dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.kotlincodes.roomdatabasekotlin.model.UserModel

@Dao
interface UserDao {

    @Insert
    fun insert(user:UserModel)

    @Update
    fun update(user:UserModel)

    @Update
    fun delete(user:UserModel)

    @Query("SELECT * FROM USERS")
    fun getAllUsers():List<UserModel>

    @Query("SELECT * FROM USERS WHERE id==:id")
    fun getUserWithId(id:Int):UserModel
}

Creating Database

To create a database we need to define an abstract class that extends RoomDatabase. This class is annotated with @Database, lists the entities contained in the database, and the DAOs which access them.

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.kotlincodes.roomdatabasekotlin.model.UserModel


@Database(entities = [UserModel::class], version =1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
    abstract fun users():UserDao


    companion object {
        private var INSTANCE: AppDatabase? = null
        fun getAppDatabase(context: Context): AppDatabase? {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java, "room-kotlin-database"
                ).build()
            }
            return INSTANCE
        }

        fun destroyInstance() {
            INSTANCE = null
        }
    }
}

Now we are ready to access the database using Room.

Make sure that you are not performing any database operations on the main thread. We need to execute all database operations in a separate thread otherwise the application will crash.

Initialize

val locaDb= AppDatabase.getAppDatabase(this)!!

Insert

locaDb.users().insert(user)

Update

locaDb.users().update(user)

Delete

locaDb.users().update(user)

That’s it!! I have created a repo with a small project with Room database operations Here