RoomDB

BongKu·2023년 6월 18일
0

Android

목록 보기
5/30
post-thumbnail

RoomDB ?

RoomDB 는 안드로이드에서 SQLite 데이터베이스를 쉽게 사용할 수 있도록 도와주는 영구 저장소 라이브러리입니다.

일반적인 사용 사례로 네트워크에 액세스할 수 없을 때도 사용자가 오프라인 상태로 계속 콘텐츠를 탐색할 수 있도록 관련 데이터를 캐시하는 것입니다.

기본 구성요소


Room에는 다음 3가지 주요 구성요소가 있습니다.

  • 데이터베이스 클래스 : 데이터베이스를 보유하고 앱의 영구 데이터와의 기본 연결을 위한 기본 액세스 포인트 역할을 합니다.
  • 데이터 항목 : 앱 데이터베이스의 테이블을 나타냅니다.
  • 데이터 액세스 객체(DAO) : 앱이 데이터베이스의 데이터를 쿼리, 업데이트, 삽입, 삭제하는 데 사용할 수 있는 메서드를 제공합니다.

데이터베이스 클래스는 데이터베이스와 연결된 DAO 인스턴스를 앱에 제공합니다. 그러면 앱은 DAO를 사용하여 데이터베이스의 데이터를 연결된 데이터 항목 객체의 인스턴스로 검색할 수 있게 됩니다. 앱은 정의된 데이터 항목을 사용하여 상응하는 테이블의 행을 업데이트하거나 삽입할 새 행을 만들 수도 있습니다. 그림 1은 다양한 Room 구성요소 간 관계를 보여줍니다.

예제

dependency 추가

dependencies {
    val room_version = "2.5.0"

    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 - Kotlin Extensions and Coroutines support for Room
    implementation("androidx.room:room-ktx:$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")
}

데이터 항목 정의

@Entity(tableName = "interest_coin")
data class InterestCoinEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val coin_name: String
)

Room 항목을 @Entity 주석이 달린 클래스로 정의합니다. Room 항목에는 기본 키를 구성하는 하나 이상의 열을 비롯하여 데이터베이스의 상응하는 테이블에 있는 각 열의 필드가 포함되어 있습니다.

데이터 액세스 객채(DAO) 정의

@Dao
interface InterestCoinDAO {
    @Query("SELECT * FROM interest_coin")
    fun getAlldata() : Flow<List<InterestCoinEntity>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(interestCoinEntity: InterestCoinEntity)

    @Delete
    fun delete(interestCoinEntity: InterestCoinEntity)
}

DAO를 인터페이스나 추상 클래스로 정의할 수 있습니다. 위 예제에서는 인터페이스를 사용합니다. 어느 경우는 @Dao 주석을 달아야합니다.

메서드는 편의 메서드, 쿼리 메서드 두 가지 유형으로 정의할 수 있습니다. 위 예제에서는 쿼리 메서드 를 활용했습니다.

데이터베이스

@Database(entities = [InterestCoinEntity::class], version = 1)
abstract class CoinInfoDatabase : RoomDatabase() {
    abstract fun interestCoinDAO(): InterestCoinDAO

    companion object {
        @Volatile
        private var INSTANCE: CoinInfoDatabase? = null

        fun getDatabase(context: Context): CoinInfoDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    CoinInfoDatabase::class.java,
                    "coin_database"
                )
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}

데이터베이스를 보유할 Database 클래스를 정의합니다. 이 클래스는 데이터베이스 구성을 정의하고 영구데이터에 대한 앱의 기본 액세스 포인트 역할을 합니다.

사용

class DBRepository {
    val context = App.context()
    val db = CoinInfoDatabase.getDatabase(context)

    // InterestCoin

    fun getAllInterestCoinData() = db.interestCoinDAO().getAlldata()

    fun insertInterestCoinData(interestCoinEntity: InterestCoinEntity) = db.interestCoinDAO().insert(interestCoinEntity)

    fun deleteInterestCoinData(interestCoinEntity: InterestCoinEntity) = db.interestCoinDAO().delete(interestCoinEntity)

}

다음과 같이 CoinInfoDatabase의 추상메서드를 사용하여 DAO 인스턴스를 가져와서 데이터베이스와 상호작용할 수 있습니다.

더 자세한 내용은 아래 안드로이드 개발자 문서를 참고
https://developer.android.com/training/data-storage/room?hl=ko

profile
화이팅

0개의 댓글