// bulid.gradle (:app)
implementation "androidx.room:room-runtime:$rootProject.roomVersion"
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
// data/Plant.kt
@Entity(tableName = "plants")
data class Plant(
@PrimaryKey @ColumnInfo(name = "id") val plantId: String,
val name: String,
val description: String,
val growZoneNumber: Int,
val wateringInterval: Int = 7, // 7주일에 한번씩 물줘야됨
val imageUrl: String = ""
)
data class로 Plant Entity를 생성한다.
@PrimaryKey
: 기본키 지정
@ColumnInfo
: 테이블 구성 필드 정의
@Dao
interface PlantDao {
@Query("SELECT * FROM plants ORDER BY name")
fun getPlants(): Flow<List<Plant>>
...
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(plants: List<Plant>)
}
Flow
: SELECT 의 결과가 변경 될 때마다 변경된 결과가 Flow로 반환된다.
(실시간으로 Room DB Update)
suspend fun
: coroutine을 이용하여 background에서 동작하는 함수 생성
@Insert(onConflict = OnConflictStrategy.REPLACE)
: 기존에 같은 PrimaryKey 를 가진 Data가 있을 때 덮어 씀
// data/AppDatabase.kt
@Database(entities = [Plant::class], version = 1, exportSchema = false)
abstract class AppDatabase: RoomDatabase() {
...
}
entities
: DB 내 Table 명시
version
: DB version (Scheme가 바뀔 때마다 version 변경 필요)
exportSchema
: DB version history 기록 여부
companion object {
// 싱글톤 인스턴스화
@Volatile private var instance: AppDatabase? = null
fun getInstance(context: Context): AppDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
}
@Volatile
: “휘발성의” 라는 뜻을 지니며, 해당 변수는 메인 메모리에만 적재하게 됨
해당 어노테이션으로 접근 가능한 변수의 값을 cache를 통해 사용하지 않고
thread가 직접 main memory에 접근 하게 하여 동기화한다.
getInstance
: 성능을 위해 싱글톤으로 생성한다.
buildDatabase 함수는 추후에 작성 예정 (WorkManager 사용)