Basic Operations Using Room Database
Room Database is a library in Android that helps you store and manage data in a more structured, safer and easier way compared to using raw SQL and SQLite.
Why use Room Database?
- Uses annotations like “@Entity” , “@Dao” and “@Database” to simplify database operations and schema definitions.
- Reduces the amount of boilerplate code needed for common database operations
- Provides compile-time verification for Sql queries, ensuring thier syntax and structure are valid before the app runs.
- Provides a type-safe way to interact with database, reducing runtime errors.
- Enforces thread safety, allowing database operations on background threads.
- Built in support for transactions ensures data integrity.
- Seamleassly integrates with LiveData and ViewModel, allowing reactive and observable data patterns.
- Works well with lifecycle-aware components, making it easier to manage data updates in sync with the UI lifecycle.
- Provides structured migration paths and versioned schemas, making database upgrades easier to manage.
Setting Up Room
1. Adding plugins
Kapt (Kotlin Annotation Processing Tool) and KSP(Kotlin Symbol Processing ) are tools used to handle annotation processing in Kotlin. Since, both does pretty much same job you can use any one of them. Kapt is a traditional and stable choice, while KSP offers more of modern and efficient approach.
To use the following plugin and dependency, add them to your module- level build.gradle.kts file:
plugins{
...
kotlin("kapt")
}dependencies{Get Anjali Verma’s stories in your inbox
Join Medium for free to get updates from this writer.
val roomVersion = "2.6.1"
implementation("androidx.room:room-ktx:$roomVersion")
androidTestImplementation("androidx.room:room-testing:$roomVersion")
implementation("androidx.room:room-runtime:$roomVersion")
kapt("androidx.room:room-compiler:$roomVersion")
}
You can refer to Migrate from kapt to KSP | Android Studio | Android Developers for using ksp plugin and dependencies.
2. Create Entity
An entity represents a table within the database. “@Entity” maps a java or a kotlin class to a database table.
@Entity(tableName = "userTable")
data class User(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String,
val age: Int
)3. Create DAO (Data Acess Object):
DAO is used to acess data from database. “@Dao” abstracts SQL queries into methods.
@Dao
interface UserDao{
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(user: User)
@Update
fun update(user: User)
@Delete
fun delete(user: User)
@Query("SELECT * FROM userTable order by id ASC")
suspend fun getAllUsers(): List<User>
}4. Create and Build the Database
The “@Database” annotation is used to define the main database class, which serves as the database holder and the main access point for the underlying connection to your app’s SQLite database. This class is an abstract class that extends RoomDatabase. It ties together the database schema, which includes the entities (tables), and the data access objects (DAOs) that contain methods for accessing the database.
- Create the Database:
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}- Build the Database:
companion object{
@Volatile
private var INSTANCE : AppDatabase?=null
fun getDatabase(context: Context):AppDatabase{
return INSTANCE?: synchronized(this){
val instance= Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app_database"
).build()
INSTANCE=instance
instance
}
}
}CRUD Operations
Now, we can perform CRUD operations using the DAO methods.
val database = AppDatabase.getInstance(context)
val userDao = database.userDao()
// Insert
val newUser = User("Alice",30)
userDao.insert(newUser)
//Update
newUser.age = 31
userDao.update(newUser)
// Delete
userDao.delete(newUser)
//Get all Users
val users = userDao.getAllUsers()








