Room

what is it?

benefits?

Set up


 def room_version = "2.6.1"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

    // To use Kotlin annotation processing tool (kapt)
    kapt "androidx.room:room-compiler:$room_version"
    // To use Kotlin Symbol Processing (KSP)
    ksp "androidx.room:room-compiler:$room_version"

    // optional - RxJava2 support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // optional - RxJava3 support for Room
    implementation "androidx.room:room-rxjava3:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "androidx.room:room-guava:$room_version"

    // optional - Test helpers
    testImplementation "androidx.room:room-testing:$room_version"

    // optional - Paging 3 Integration
    implementation "androidx.room:room-paging:$room_version"

Screenshot 2024-02-21 at 8.35.13 AM.png

Three major components in Room

Database class

// Song and Album are classes annotated with @Entity.
@Database(version = 1, entities = [Song::class, Album::class])
abstract class MusicDatabase : RoomDatabase {
  // SongDao is a class annotated with @Dao.
  abstract fun getSongDao(): SongDao

  // AlbumDao is a class annotated with @Dao.
  abstract fun getArtistDao(): ArtistDao

  // SongAlbumDao is a class annotated with @Dao.
  abstract fun getSongAlbumDao(): SongAlbumDao
}

Data entities

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

Data access objects

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

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

    @Query("SELECT * FROM user 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)
}

Usage

After you've defined the data entity, the DAO and the database object, you can use the following code to create an instance of the database


val db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "database-name"
        ).build()

Where do you trigger this build code?


val userDao = db.userDao()  
val users: List<User> = userDao.getAll()

Where do you use this?

https://developer.android.com/training/data-storage/room