[Android] Sunflower 클론코딩 (22.06.07)

유재민·2022년 6월 7일
0

Sunflower

목록 보기
6/12
post-thumbnail

Room

// bulid.gradle (:app)

implementation "androidx.room:room-runtime:$rootProject.roomVersion"
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"


1. Entity

  • Table 정의
// 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 : 테이블 구성 필드 정의



2. DAO

  • Plant 클래스를 위한 DAO(Data Access Object) 생성
@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가 있을 때 덮어 씀



3. Database

  • 데이터베이스 객체 생성
  • 추상 클래스
  • 데이터베이스 객체를 인스턴스 할 때, 싱글톤으로 구현하기를 권장 (인스턴스에 엑세스 해야하는 경우가 잘 없고, 객체 생성 비용이 크기때문)
// 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 사용)

profile
유잼코딩

0개의 댓글