Junior — Middle
Could you explain what the Room component in Android is and how it is used for database operations?
sobes.tech AI
Answer from AI
Room is a library in Android Jetpack that simplifies working with the SQLite database. It provides an abstraction over SQLite, allowing you to work with the database through objects and annotations, which reduces boilerplate code and errors.
Main components of Room:
- Entity — a class that describes a table in the database.
- DAO (Data Access Object) — an interface with methods for data access (insertion, update, queries).
- Database — an abstract class that links Entity and DAO and creates the database.
Example:
@Entity(tableName = "users")
data class User(
@PrimaryKey val id: Int,
val name: String
)
@Dao
interface UserDao {
@Query("SELECT * FROM users")
fun getAll(): List<User>
@Insert
fun insert(user: User)
}
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
Using Room allows safe and convenient work with a local database in Android applications.