database is a part of the Android Jetpack which is persistence library. Room database is an abstraction layer over SQLite which allow us more robust database access. Room is now can be considered as a better approach for data persistence in comparison of  SQLite Database. It help us to work with SQLite Database objects in most  easier way  in your app, it reduce the amount of boilerplate code and verifying SQL queries at time of compilation

Advantages of Room

  • Room provide Compile-time verification of SQL queries means each @Query and @Entity is checked at the compile time in room databases.
  • In room data base it is easy with migration class.
  • It reduce boilerplate code
  • It is design to work with live data and view model

Disadvantages of SQLite

  • SQLite does not provide compile-time verification of raw SQL queries. Let’s suppose, if we write a SQL query with a wrong column name that does not exist in real database then it will through exception at run time and you can not find this issue during compile time.
  • Updating database, changing Schema is time-consuming and error-prone.
  • To convert between SQL queries and Java data objects (POJO) you need a lots of boilerplate code.

Room vs SQLite

Room is an ORM, which means it is Object Relational Mapping library. In some other words, Room can map our database objects to Java objects. 

Difference between SQLite and Room persistence library:-

  • In the case of SQLite, SQLite does not provide compile-time verification of raw SQLite queries. While in Room we can do SQL validation at time of compilation.
  • In case of SQLite you have to use lots of boilerplate code while converting between SQL queries and Java data objects. But, Room maps our database objects to Java Object without use of any boilerplate code means you don’t need boilerplate code any more.
  • IN SQLite as your schema changes, you have to update the affected SQL queries manually. But Room solves this problem you don’t need to update SQL queries manually.
  • Room is built to work with LiveData ,View model and RxJava .while SQLite does not.

Room contain three main components of Room DB :

  • Entity
  • Dao
  • Database

1. Entity

Entity represents a table in the database. Room creates a table for every class that define with @Entity annotation.

Entities annotations

There are some useful annotations and their attributes.

@Entity — any model class that define with  this annotation will have a mapping table in DB

  • foreignKeys — It defines names of foreign keys
  • indices — It indicate list of indicates on the table
  • primaryKeys — It indicate names of entity primary keys
  • tableName- It define table name and it is optional 

@PrimaryKey — as its name suggest, this annotation indicate to the primary key of the entity which is  auto generated. 

 If we set it to true, then SQLite will  generate a unique id for the column

@PrimaryKey(autoGenerate = true)

@ColumnInfo — it specify custom information about column

@ColumnInfo(name = “column_name”)

@Ignore — It ignore the field that you don’t want to be converted into a column:

@Embeded —Embeded anotation tell Room that the properties on the annotated object should be represented as columns on the same entity.

2. Dao

In DAOs we define the the methods that access the database. When we use SQLite, we use the Cursor objects. But Room don’t need the Cursor anymore and it has annotations that allow us to define our queries in the Dao class.

3. Database

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

The database class should satisfy the following conditions:

  • It should be an abstract class that extends RoomDatabase.
  • It include the list of entities which is associated with the database within the annotation.
  • It contain an abstract method that has 0 arguments and will return the class that is annotated with @Dao.

Let’s see an example how to work with Room data base.

Step 1:- Add dependancies

//dependancy for using room.  
implementation ‘androidx.room:room-runtime:2.2.5’
annotationProcessor ‘androidx.room:room-compiler:2.2.5’

//dependancy for using lifecycle extensions for room.  
implementation ‘androidx.lifecycle:lifecycle-extensions:2.2.0’
annotationProcessor ‘androidx.lifecycle:lifecycle-compiler:2.2.0’

Step 2: Create a Model Class

Room database will create a table for each class which has been annotated with @Entity.

  • You have to annotate the class with @Entity and to set the name of the table use the tableNameproperty .
  • You have to set the primary key by adding the “@primaryKey” annotation to fields  which you want to generate automatically
  • You have to set the name of the columns for the class fields with the help of @ColumnInfo(name = “column_name”) annotation. 
@Entity(tableName = “user_data_table")
data class User(

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = “user_id")
    var id: Int,

    @ColumnInfo(name = “user_name")
    var name: String,

    @ColumnInfo(name = “user_email")
    var email: String

)

Step 3 :- Create DAO (Data Access Objects) Interface which have methods to access the Database

@Dao
interface UserDAO {

    @Insert
    suspend fun insertUser(user:User) : Long

    @Update
    suspend fun updateUser(user:User) : Int

    @Delete
    suspend fun deleteUser(user:User) : Int

    @Query("DELETE FROM user_data_table")
    suspend fun deleteAll() : Int

    @Query("SELECT * FROM user_data_table")
    fun getAllUsers():Flow<List<User>>

}

Step 4 :- Create the database

Now we have to create database and for this we have to extend the RoomDatabase.

@Database(entities = [User::class], version = 1)
abstract class UserDatabase : RoomDatabase() {
    abstract val userDAO: UserDAO

    companion object {
        @Volatile
        private var INSTANCE: UserDatabase? = null
        fun getInstance(context: Context): UserDatabase {
            synchronized(this) {
                var instance = INSTANCE
                if (instance == null) {
                    instance = Room.databaseBuilder(
                        context.applicationContext,
                        UserDatabase::class.java,
                        “user_data_database"
                    ).build()
                }
                return instance
            }
        }
    }
}

Things to keep remember:

  • This is an abstract class which has to extend from RoomDatabase.
  • It must to be annotated with @Database, which receives a list of entities with all the classes that compose the database .We also have to provide a database version.
  • We must to declare an abstract function for each of the entities which have included in the @Database annotation, this function must have to return the correspondentDAO (A class annotated with @Dao).
Step 5 — CRUD operation on Room Database
Now create methods to define C

class UserRepository(private val dao: UserDAO) {

    val users = dao.getAllUsers()

    suspend fun insert(user:User): Long {
        return dao.insertUser(user)
    }

    suspend fun update(user:User): Int {
        return dao.updateUser(user)
    }

    suspend fun delete(user:User: Int {
        return dao.deleteUser(user)
    }

    suspend fun deleteAll(): Int {
        return dao.deleteAll()
    }
}

You may also like...

0 Comments

No Comment.