Room 사용법 [kotlin] - android local database

앱을 만들면서 내부 로컬 db 사용이 필요했다.

sqlite를 사용하려고 관련해서 찾다가, Room을 발견했다.

 

Room이 무엇인가?

Room은 안드로이드 로컬 데이터베이스를 사용할 때 쓴다고 한다.

 

사용법

1. 의존성 추가

build.gradle파일에 dependency에 다음 코드를 추가해준다.

def roomVersion = "2.4.2"
implementation("androidx.room:room-runtime:$roomVersion")
kapt("androidx.room:room-compiler:$roomVersion")

이때 roomVersion의 경우에는 

https://developer.android.com/jetpack/androidx/releases/room?hl=ko 에서 최신 버전 확인.

 

2. plugin 추가

build.gradle 파일에 plugins에 아래 코드를 추가해주세요.

id 'kotlin-kapt'

3. 필수 구성요소

room에는 필수 구성요소가 3개 있습니다. [Database, entity, Dao]

 

4. Entity 

엔티티의 경우에는 기본 키를 구성하는 하나 이상의 열을 비롯하여 필드를 정의를 합니다.

@Entity
data class User(
    @PrimaryKey val id: Int,

    val firstName: String?,
    val lastName: String?
)

기본키는 아래와 같이 정의를 해준다. 

@PrimaryKey val id: Int

5. Dao

@Dao
public interface PlanDao{
    // 전부 가져오기
    @Query("SELECT * FROM 'Plan'")
    fun getAll() : List<Plan>

    // 삽입 하기
    @Insert
    fun insertDB(plan: Plan)

    // 삭제 하기
    @Delete
    fun delete(plan:Plan)
}

6.  Database

@Database(entities = [Plan::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun PlanDao() : PlanDao
    companion object {
        private var instance: AppDatabase? = null

        @Synchronized
        fun getInstance(context: Context): AppDatabase? {
            if (instance == null) {
                instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "database-contacts"
                )
                    .allowMainThreadQueries()
                    .build()
            }
            return instance
        }
    }
}

7. db 확인 법

안드로이드 스튜디오 하단에 app inspection에서 Database inspector를 통해 실시간 확인이 가능합니다.