===== 플러그인 설치 ===== 다음을 build.gradle.kts(Module : app)에 추가한다. //Room 버전 val room_version:String = "2.6.1" // Room implementation("androidx.room:room-runtime:$room_version") implementation("androidx.room:room-ktx:$room_version") // Kotlin annotation processingtool kapt ("androidx.room:room-compiler:$room_version") 플러그인에도 다음을 추가해야 한다. plugins { ... id("kotlin-kapt") } 참고로 2024. 7. 29. 현재 구글검색을 하면 나오는 gradle script 예제들은 Groovy 언어에 기반한 것이다((https://stackoverflow.com/questions/77038956/cant-use-def-keyword-in-build-gradle-kts-error-unresolved-reference-def)). 그런데 우리는 코틀린 스크립립트 즉, kts파일을 이용할 것이므로 코틀린 언어를 사용해야 한다. 따라서 위와 같이 써야 플러그인을 정상적으로 다운 받을 수 있다. ===== 뼈대 만들기 ===== ==== 1. 데이터 클래스 생성 ==== 데이터 클래스를 생성하여 구조화된 자료를 만들자. 이를테면 다음과 같이 만들 수 있을 것이다. data class Todo( var id : Int = 0, var title : String, var createdAt : LocalDateTime ) [[android:클래스와리스트를사용하기|데이터 클래스 예시]]를 참조하자 ==== 2. 엔티티 생성 ==== 위 데이터 클래스에 애노테이션을 추가하면 엔티티를 만들 수 있다. 데이터 클래스 위에 "@Entity" 애노테이션을 추가하면 데이터베이스에서 다루틑 엔티티가 된다. 그 외에 데이터베이스에서 다루는 개념들도 애노테이션으로 추가 가능하다. 이를테면 프라이머리키는 "@PrimaryKey"로 추가하면 된다. 다음은 그 예시다. Contact.kt를 다음과 같이 만들었다. package com.dklaw.gogo2.database import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Contact( val firstName : String, val lastName : String, val phoneNumber : String, val phoneNumber2 : String, val officeNumber : String, val faxNumber : String, val email : String, val address : String, val idCardAddress : String, val zipcode : String, val socialNumber : String, val work : String, val workAddress : String, val etc : String, val photo : String, @PrimaryKey(autoGenerate = true) val id : Int = 0 ) ==== 2. DAO 생성 ==== 다음과 같이 ContactDAO.kt 파일을 만든다. package com.dklaw.gogo2.database import androidx.room.Dao import androidx.room.Delete import androidx.room.Query import androidx.room.Upsert import kotlinx.coroutines.flow.Flow @Dao interface ContactDAO { @Upsert suspend fun upsertContact(contact : Contact) @Delete suspend fun deleteContact(contact: Contact) @Query("SELECT * FROM contact ORDER BY firstName ASC") fun getContactsOrderByFirstName() : Flow> @Query("SELECT * FROM contact ORDER BY lastName ASC") fun getContactsOrderByLastName() : Flow> @Query("SELECT * FROM contact ORDER BY phoneNumber ASC") fun getContactsOrderByPhoneNumber() : Flow> }