Open In App

Android Room Persistence Library in Kotlin

Last Updated : 17 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Android Room Persistence Library is one of the sets of libraries provided by Android Jetpack so as to help developers follow the best practices while eliminating boilerplate codes and reducing fragmentation. In Android applications, we often need to store structured data, and persisting that data locally is always a good idea. This way if our application crashes or gets restarted the data will not be lost and that data can be retrieved at later times. Especially when we need to show up some relevant information to the user, that needs to be present even in absence of a network, persisting data into the app comes very handy. 

Advantages of using Room Persistence Library

Room persistence library is used as an abstraction layer over SQLite for more robust database access. There are several advantages in using this library over SQLite APIs and the ease of using SQLite in a much more natural way is the most prominent one.

  • Room has this wonderful feature of compile-time verification of the SQL queries that reduces the chances of run time errors and crashes.
  • Room can return Live Data, i.e., get automatic instant updates in database reflected after fetching the data.
  • Since Room is an ORM (Object Relational Mapping) library as a user there is no need to convert the Data to Java/Kotlin Objects and vice-versa. As Room internally maps the Database objects to Java objects.
  • Room has the convenience of using annotations in place of redundant and boilerplate code sections.
  • Yet another amazing feature of Room is that here entire database schema can be changed without changes in the code. or starting from scratch.
  • Room has excellent integration with RxJava, Kotlin Coroutines, LifecycleObserver, etc.

Now since we have an idea of the amazing features that come with this library let’s dive deep into this.

Components of Room

Room has three primary components namely Database, Entity (like Tables), and DAO (Data Access Objects). Let us now discuss each of them one by one.

Database

In Room, an abstract class annotated with @Database provides an abstraction layer over the SQLite Database. This component of Room is the major access resource of relation data persisted in the application. The class serving this purpose must be abstract, including a list of entities associated with the database, containing an abstract method with no arguments and return type same as the interface annotated with @Dao. For example, here is a code snippet that shows one such annotated class named AppDatabase that inherits from RoomDatabase.

@Database(entities = [ToDoModel::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun toDoDao(): ToDoDao

    // Code Lines
}

Entity

Entity is nothing but a class representing columns of a database table as data fields. This class is annotated with @Entity annotation. All the fields in the class must be accessible, i.e. either public or with getter/setter methods. A constructor also must be present to create entry instances. In Kotlin, the best way is to use a data class that provides the constructor, getter, and setter methods all implemented intrinsically. From the knowledge of SQL, it is known that each entity class must have at least one primary key. For this, that particular field can be annotated with @PrimaryKey annotation to define a single field primary key or in case there are more than one primary key then the attribute of @Entity annotation for multiple fields can be used. We can also annotate fields with @Ignore annotation if we don’t wish to persist in those fields. Here we have a To-do model class as an example with variables title, description, and an id which is autogenerated and acting as the primary key.

@Entity
data class ToDoModel (
        var title: String,
        var description: String,
        // autoGenrate -attribute to
        // automatically assign primary keys.
        @PrimaryKey(autoGenerate = true)    
        var id: Long = 0
)

Dao (Data Access Objects)

As discussed above Room allows developers to use SQL queries in a much robust and natural way. Here it is when we see this happening. Dao is an interface annotated with @Dao annotation which possesses all the SQL queries we need to have in usage. This is done using various annotations like @Insert, @Update, @Query, @Delete, etc. that reduce the boilerplate like a magic-making adding or removing queries super easy. It works as an API providing access to the database. These methods are executed on the thread calling them thus we must make sure that they are not called using the main (UI) thread. In case we need to work with multiple entities we need not copy various methods from one Dao to another as it supports inheritance as well. For this just create a generic BaseDao<T> class, and define the various @Insert, @Update, and @Delete methods there. Below is a simple Dao interface having insertion, updating, and querying methods. 

@Dao
interface ToDoDao {
    @Insert()
    suspend fun insertTask(toDoModel: ToDoModel): Long
    
    @Update(onConflict = OnConflictStrategy.REPLACE)
    suspend fun updateTask(toDoModel: ToDoModel): Int

    @Query("SELECT * FROM ToDoModel WHERE isDone == 0")
    fun getTask(): LiveData<List<ToDoModel>>


    @Query("DELETE FROM ToDoModel WHERE id=:uid")
    fun deleteTask(uid: Long)
}

Room Library Architecture

After going through the components of the Room Library we have an idea of how each of them works individually and what are their roles. Now based on this we have this illustration representing their functionalities. We can see Room Database instance acquired by us is used to get access over Dao which in turn has all query functions and control over entities. By using these entities to get and set data as mentioned through the queries in Dao, the data is persisted.   

Room Persistence Library Architecture

Implementation and Setup for using Room Database in Applications

For the complete project please refer to this article: How to Build a Grocery Android App using MVVM and Room Database?


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads