Room Database with MVVM(Part-I)

Rajendrakumar Dabhi
3 min readOct 3, 2021

The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In particular, Room provides the following benefits:

  • Compile-time verification of SQL queries.
  • Convenience annotations that minimise repetitive and error-prone boilerplate code.
  • Streamlined database migration paths.

Setup

To use Room in your app, add the following dependencies to your app’s build.gradle file:

dependencies {
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
}

Room Database Consist Below Components:

Data entity

The following code defines a User data entity. Each instance of User represents a row in a user table in the app's database.

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

TableName:Here you can provide the name of the table if you want to give different table name than the class name, you can also provide foreign key by comma separating in this entity constructor.

Primarykey: To make any column primary key

Columninfo: To provide different name of the column and if you want that your column name same as the property name then you don’t need to add this annotation.

You can also add annotation in you API model class to make it entity.

Data access object (DAO)

The following code defines a DAO called UserDao. UserDao provides the methods that the rest of the app uses to interact with data in the user table.

Here in the DAO class you can use annotations for different different operation to be performed on the database like Insert,Update,Delete,Query.

so all your SQL queries and database related operation added here,

@Dao
interface UserDao {
@Query("SELECT * from User")
fun getUsers():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

@Insert
fun insertAll(vararg users: User)

@Delete
fun delete(user: User)
}

Database

The following code defines an AppDatabase class to hold the database. AppDatabase defines the database configuration and serves as the app's main access point to the persisted data. The database class must satisfy the following conditions:

  • The class must be annotated with a @Database annotation that includes an entities array that lists all of the data entities associated with the database.
  • The class must be an abstract class that extends RoomDatabase.
  • For each DAO class that is associated with the database, the database class must define an abstract method that has zero arguments and returns an instance of the DAO class.
@Database(entities = [User::class], version = 1)
abstract class LocalDatabase : RoomDatabase() {

abstract fun UserDao(): UserDao //all your DAO will be added here
companion object {
private val DB_NAME: String="mvvmsampledb" //Name of your database

@Volatile
private var INSTANCE: LocalDatabase? = null
// Here we are creating singleton so it will give same object every time instead of creating new.
internal fun getDatabase(context: Context): LocalDatabase? {
if (INSTANCE == null) {
synchronized(LocalDatabase::class.java) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context.getApplicationContext(),
LocalDatabase::class.java, DB_NAME
).build()
}
}
}
return INSTANCE
}
}
}

Here we have completed the Basics things to be done for adding Room database,In next part we will see the integration of Room Db with MVVM Architecture.

--

--