Room Database

Understanding Room Database and its implementation

Introduction to Room Database

Room Android Architecture Components का एक SQLite database abstraction layer है। यह SQLite database को use करने का एक simple और efficient way provide करता है।

Room is an SQLite database abstraction layer in Android Architecture Components. It provides a simple and efficient way to use SQLite database.

Key Features (मुख्य विशेषताएं):

  • Room compile-time verification provide करता है
  • Room provides compile-time verification
  • Room boilerplate code को reduce करता है
  • Room reduces boilerplate code
  • Room LiveData और RxJava के साथ integrate होता है
  • Room integrates with LiveData and RxJava
  • Room type-safe queries provide करता है
  • Room provides type-safe queries

Room Components (रूम कंपोनेंट्स)

Room के main components:

Main components of Room:

Component (कंपोनेंट) Description (विवरण)
Entity Database table को represent करता है
Entity Represents a database table
DAO Database operations को define करता है
DAO Defines database operations
Database Database holder और main access point होता है
Database Database holder and main access point

Implementation Example (इम्प्लीमेंटेशन उदाहरण)

Room Database को implement करने का example:

Example of implementing Room Database:

// Entity
@Entity(tableName = "users")
data class User(
    @PrimaryKey val id: Int,
    val name: String,
    val age: Int
)

// DAO
@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun getAllUsers(): LiveData>

    @Insert
    suspend fun insertUser(user: User)

    @Update
    suspend fun updateUser(user: User)

    @Delete
    suspend fun deleteUser(user: User)
}

// Database
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    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
            }
        }
    }
}

// Repository
class UserRepository(private val userDao: UserDao) {
    val allUsers: LiveData> = userDao.getAllUsers()

    suspend fun insert(user: User) {
        userDao.insertUser(user)
    }

    suspend fun update(user: User) {
        userDao.updateUser(user)
    }

    suspend fun delete(user: User) {
        userDao.deleteUser(user)
    }
}

Database Migrations (डेटाबेस माइग्रेशन्स)

Room Database migrations के examples:

Examples of Room Database migrations:

// Migration from version 1 to 2
val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("ALTER TABLE users ADD COLUMN email TEXT")
    }
}

// Migration from version 2 to 3
val MIGRATION_2_3 = object : Migration(2, 3) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("CREATE TABLE IF NOT EXISTS users_new (id INTEGER PRIMARY KEY, name TEXT, age INTEGER, email TEXT, phone TEXT)")
        database.execSQL("INSERT INTO users_new (id, name, age, email) SELECT id, name, age, email FROM users")
        database.execSQL("DROP TABLE users")
        database.execSQL("ALTER TABLE users_new RENAME TO users")
    }
}

// Database with migrations
@Database(entities = [User::class], version = 3)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    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"
                )
                .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
                .build()
                INSTANCE = instance
                instance
            }
        }
    }
}

Best Practices (सर्वोत्तम प्रथाएं)

Room Database के साथ काम करने के best practices:

Best practices for working with Room Database:

  • Database Operations: Database operations को background thread पर perform करें
  • Database Operations: Perform database operations on background thread
  • Migrations: Database schema changes के लिए migrations का use करें
  • Migrations: Use migrations for database schema changes
  • Type Safety: Type-safe queries का use करें
  • Type Safety: Use type-safe queries
  • Testing: Room Database को easily testable बनाएं
  • Testing: Make Room Database easily testable