ROOM DB
Image Credit / Source : Zorbey Torunoğlu
Room Database
Room is a persistence library provided by Android as part of Jetpack components. It acts as an abstraction layer over SQLite to allow more robust database handling while providing easier and cleaner APIs. Room is used to manage local data storage in Android apps and enables developers to interact with the database using a more convenient, type-safe, and less error-prone approach.
How Room Works
Room organizes your database interactions into three main components:
- Entity: Represents a table within the database.
- DAO (Data Access Object) : Interface or Contains methods for accessing the database.
- Database : Holds the database and serves as the main access point for the underlying connection.
Entity
An Entity represents a table in the database. Each instance of the Entity corresponds to a row in the table. Let’s explore its components:
An Entity is a data class in Kotlin annotated with
@Entity. Each field in the class represents a column in the table
Annotations Used in Entities
@Entity(tableName = "users_table")
data class User(
@PrimaryKey(autoGenerate = true)
val id: Int
@ColumnInfo(name = "user_email")
val email: String
@ColumnInfo(defaultValue = "unknown")
val status: String
@Ignore
val temporaryField: String
@Embedded val address: Address
)- @Entity
- Marks the class as an Entity.
tableName: Optional parameter to specify a custom table name. Default is the class name.
@Entity
data class User()
@Entity(tableName = "users_table")
data class User()2. @PrimaryKey
- Marks a field as the primary key.
- Use
autoGenerate = truefor auto-increment IDs.
@PrimaryKey(autoGenerate = true)
val id: Int3. @ColumnInfo
- Customizes your table column name or settings.
@Entity
data class User(
@ColumnInfo(name = "user_email")
val email: String
@ColumnInfo(defaultValue = "unknown")
val status: String
@ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val age: Int
)4. @Ignore
- Excludes a field from the database schema.
@Ignore
val temporaryField: String5. @Embedded
- Used for complex data types (nested objects). Combines the fields of the nested object as columns.
@Entity
data class User(
@PrimaryKey val id: Int,
@Embedded val address: Address
)
data class Address(val city: String, val street: String)6. @Relation Defines relationships between entities for one-to-one or one-to-many mappings.
data class UserWithPosts(
@Embedded val user: User,
@Relation(
parentColumn = "id",
entityColumn = "userId"
)
val posts: List<Post>
)7. @TypeConverters Allows custom data types (e.g., Date, List, Enum) to be stored in the database.
class Converters {
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
return value?.let { Date(it) }
}
@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
return date?.time
}
}
@Entity
@TypeConverters(Converters::class)
data class User(
val birthDate: Date
)DAO (Data Access Object)
The DAO is the interface used to interact with the database which Annotated with
@Dao. It provides methods to perform operations like Insert, Query, Update, and Delete.
Why DAO?
- Keeps the database logic separate from the app logic.
- Allows clean, reusable, and testable code.
Annotations in DAO
@Dao
interface UserDao {
@Insert
suspend fun insertUser(user: User)
@Query("SELECT * FROM users")
suspend fun getAllUsers(): List<User>
}@Dao
- Marks an interface or abstract class as a DAO.
- This is the base annotation for defining a DAO.
@Dao
interface UserDao {
@Insert
suspend fun insertUser(user: User)
@Insert
suspend fun insertUser(user: User): Long
@Insert
suspend fun insertAllUsers(users: List<User>): List<Long>
@Query("SELECT * FROM users")
suspend fun getAllUsers(): List<User>
@Query("SELECT COUNT(*) FROM users")
suspend fun getUserCount(): Int
// updateUserName("%Abhi", "Blr%")
@Query("SELECT * FROM users WHERE tvName LIKE :userName AND Address Like :address ORDER BY name ASC")
suspend fun updateUserName(userName: String, address: String) : LiveData<List<User>>
@Query("SELECT * FROM users WHERE tvName LIKE :userName AND Address Like :address ORDER BY name ASC")
suspend fun updateUserName(userName: String, address: String) : Flow<List<User>>
/**
Wildcards in LIKE
%: Matches zero or more characters.
_: Matches exactly one character.
Examples:
LIKE 'Jo%': Matches "John", "Joanne", "Jonathan".
LIKE '%hn': Matches "John", "Ethan".
LIKE 'J_hn': Matches "John" but not "Joanne".
**/
@Update
suspend fun updateUser(user: User): Int
@Query("UPDATE users_profile_details SET tvName = :userName WHERE id = :userId")
suspend fun updateUserName(userName: String, userId: String) : Int
@Delete
suspend fun deleteUser(user: User): Int
@Query("DELETE FROM users WHERE id = :userId")
suspend fun deleteUserById(userId: Int): Int
@Query("DELETE FROM users_profile_details WHERE id = :id")
suspend fun deleteUserByID(id: String)
}@Insert
- Used to insert data into a table.
- Supports:
- Single object insertion.
- Multiple objects as a list.
- Bulk insertion.
@Insert
suspend fun insertUser(user: User): Long
@Insert
suspend fun insertAllUsers(users: List<User>): List<Long>@Query
- Allows custom SQL queries for Read, Update, or Delete operations.
- Supports
SELECT,UPDATE,DELETE, and more.
@Query("SELECT * FROM users WHERE id = :userId")
suspend fun getUserById(userId: Int): User
@Query("SELECT COUNT(*) FROM users")
suspend fun getUserCount(): Int
@Query("DELETE FROM users WHERE id = :userId")
suspend fun deleteUserById(userId: Int): Int
@Query("UPDATE users_profile_details SET tvName = :userName WHERE id = :userId")
suspend fun updateUserName(userName: String, userId: String) : Int@Update
- Used to update existing rows in a table.
- The entity object must have a primary key for Room to identify the row to update.
- Returns: The number of rows updated.
Get Abhishek Rai’s stories in your inbox
Join Medium for free to get updates from this writer.
@Update
suspend fun updateUser(user: User): Int
@Query("UPDATE users_profile_details SET tvName = :userName WHERE id = :userId")
suspend fun updateUserName(userName: String, userId: String) : Int@Delete
- Used to delete specific rows in a table.
- The entity object must match the table row (by primary key).
- Returns: The number of rows deleted.
@Delete
suspend fun deleteUser(user: User): Int
@Query("DELETE FROM users_profile_details WHERE id = :id")
suspend fun deleteUserByID(id: String)@Transaction
- Ensures the atomicity of a set of operations.
- Useful for multiple queries that need to be treated as a single transaction.
@Transaction
suspend fun replaceUser(oldUser: User, newUser: User) {
deleteUser(oldUser)
insertUser(newUser)
}Database
The Database class in Room is the central component that serves as the main access point to the underlying SQLite database. It is an abstract class annotated with
@Databaseand extendsRoomDatabase.
- The main access point to your database which Annotated with
@Database. - Must be an abstract class that extends
RoomDatabase. - Specifies the list of Entities , Database version and Schema.
import android.content.Context
import androidx.room.Room
@Database(entities = [User::class, Post::class], version = 1, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun postDao(): PostDao
// Create a companion object for database creation
companion object {
//DataBase Name
private const val DATABASE_NAME = "app_database"
// Singleton instance of the database
@Volatile
private var instance: AppDatabase? = null
// --------------------------------------------------------------
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
DATABASE_NAME
).build()
INSTANCE = instance
instance
}
}
// --------------------------------------------------------------
//Get the database instance
fun getInstance(context: Context): AppDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
//Create DataBase instance
private fun buildDatabase(context: Context): AppDatabase {
return Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
DATABASE_NAME,
)
//.addMigrations(MIGRATION_1_2) //Thi code is for migration
.fallbackToDestructiveMigration() // Use this only during development
.build()
}
}
}
Key Points About the Database Class
1. Annotation: @Database
The @Database annotation defines:
- Entities: The list of data classes that represent database tables.
- Version: The schema version of the database.
- Export Schema: Whether to export the database schema for version control.
@Database(entities = [User::class, Post::class], version = 1, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun postDao(): PostDao
}2. Singleton Design Pattern
- Only one instance of the database is created to ensure efficient resource use.
- Room provides a
Room.databaseBuilder()method to create or retrieve the instance.
import android.content.Context
import androidx.room.Room
class DatabaseInstance private constructor(context: Context) {
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
}
}
}
}3. Abstract Methods
- The database class defines abstract methods to access the DAOs.
- These methods return the DAO interfaces annotated with
@Dao.
abstract fun userDao(): UserDao
abstract fun postDao(): PostDao4. Database Schema Versioning
- The
versionattribute in@Databasespecifies the schema version. - If the schema changes (e.g., adding a column), the version must be incremented, and a migration strategy should be defined.
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE users ADD COLUMN age INTEGER DEFAULT 0 NOT NULL")
}
}
val db = Room.databaseBuilder(context, AppDatabase::class.java, "app_database")
.addMigrations(MIGRATION_1_2)
.build()
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Example:
Foreign Key Usage
Let’s create a database with two tables:
- User: Represents the parent table.
- Post: Represents the child table, with a foreign key referencing the
idof theUsertable.
Parent Table: User
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "users")
data class User(
@PrimaryKey(autoGenerate = true) val id: Int,
val name: String,
val email: String
)
Child Table: Post
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
@Entity(
tableName = "posts",
foreignKeys = [
ForeignKey(
entity = User::class, // Reference parent entity
parentColumns = ["id"], // Parent column (primary key)
childColumns = ["userId"], // Child column (foreign key)
onDelete = ForeignKey.CASCADE // Action on parent deletion
)
]
)
data class Post(
@PrimaryKey(autoGenerate = true) val postId: Int,
val userId: Int, // Foreign key column
val title: String,
val content: String
)Define DAOs
UserDao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface UserDao {
@Insert
suspend fun insertUser(user: User): Long
@Query("SELECT * FROM users")
suspend fun getAllUsers(): List<User>
}PostDao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface PostDao {
@Insert
suspend fun insertPost(post: Post): Long
@Query("SELECT * FROM posts WHERE userId = :userId")
suspend fun getPostsByUser(userId: Int): List<Post>
}Define the Database
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [User::class, Post::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun postDao(): PostDao
}Using the Foreign Key Relationship
import android.content.Context
import androidx.room.Room
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
// Initialize Room Database
val db = Room.databaseBuilder(
context = applicationContext,
AppDatabase::class.java,
"app_database"
).build()
val userDao = db.userDao()
val postDao = db.postDao()
// Insert a User
val userId = userDao.insertUser(User(0, "John Doe", "john@example.com"))
// Insert a Post linked to the User
postDao.insertPost(Post(0, userId.toInt(), "My First Post", "This is the content."))
val posts = postDao.getPostsByUser(userId.toInt())
posts.forEach { post ->
println("Post Title: ${post.title}, Content: ${post.content}")
}
}— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Write a DAO with a JOIN Query
Below is the Example of Join but make sure to create Parent & Child Table like above — user & post and one more data class which all field you are selecting using Query in JOIN
import androidx.room.Dao
import androidx.room.Query
@Dao
interface UserPostDao {
@Query("""
SELECT
users.name AS userName,
users.email AS userEmail,
posts.title AS postTitle,
posts.content AS postContent
FROM users
INNER JOIN posts ON users.id = posts.userId
WHERE users.id = :userId
""")
suspend fun getUserWithPosts(userId: Int): List<UserWithPosts>
}







