Sobes.tech
Junior

What are the main components of the Room library for working with databases in Android?

sobes.tech AI

Answer from AI

Main components of the Room library:

  • @Entity: Defines a class as a table in the database. Annotated on a data class (POJO) and specifies the table name if it differs from the class name. You can define a primary key and indexes.

  • @Dao: Defines an interface or abstract class for data access objects. Contains methods for database operations (insert, update, delete, queries).

  • @Database: Defines an abstract class extending RoomDatabase. Specifies entities (tables), DAOs, and the database version. Provides a singleton instance of the database.

  • Data Access Objects (DAO): Interfaces or abstract classes annotated with @Dao. Contain methods with annotations @Insert, @Delete, @Update, @Query for data interaction.

  • RoomDatabase: An abstract class generated by Room based on a class annotated with @Database. Provides an entry point to obtain DAO instances.

  • SQL Queries: Room uses SQL for database queries, defined in @Query annotations of DAO methods.

Example structure:

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

// DAO
@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun getAll(): List<User>

    @Query("SELECT * FROM users WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): List<User>

    @Query("SELECT * FROM users 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
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

Interaction between components: AppDatabase (the implementation of RoomDatabase) provides access to the UserDao instance. The methods of UserDao execute SQL queries on the users table (represented by the User class).