사용자 도구

사이트 도구


android:room을사용하여데이터보관
room을사용하여데이터보관

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판이전 판
다음 판
이전 판
android:room을사용하여데이터보관 [2024/07/29 20:32] 이거니맨android:room을사용하여데이터보관 [2024/12/24 20:04] (현재) 이거니맨
줄 27: 줄 27:
 </WRAP> </WRAP>
  
 +
 +===== 뼈대 만들기 ===== 
 +
 +==== 1. 데이터 클래스 생성 ====
 +
 +데이터 클래스를 생성하여 구조화된 자료를 만들자. 
 +
 +이를테면 다음과 같이 만들 수 있을 것이다. 
 +
 +
 +<code kotlin>
 +data class Todo(
 +    var id  : Int = 0,
 +    var title : String,
 +    var createdAt : LocalDateTime
 +)
 +
 +
 +
 +</code> 
 +[[android:클래스와리스트를사용하기|데이터 클래스 예시]]를 참조하자
 +
 +==== 2. 엔티티 생성 ==== 
 +
 +위 데이터 클래스에 애노테이션을 추가하면 엔티티를 만들 수 있다. 
 +
 +데이터 클래스 위에 "@Entity" 애노테이션을 추가하면 데이터베이스에서 다루틑 엔티티가 된다. 
 +
 +그 외에 데이터베이스에서 다루는 개념들도 애노테이션으로 추가 가능하다. 이를테면 프라이머리키는 "@PrimaryKey"로 추가하면 된다. 
 +
 +다음은 그 예시다. 
 +
 +Contact.kt를 다음과 같이 만들었다.
 +
 +
 +<file kotlin 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
 +)
 +
 +</file>
 +
 +==== 2. DAO 생성 ==== 
 +
 +다음과 같이 ContactDAO.kt   파일을 만든다. 
 +
 +<file kotlin 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<List<Contact>>
 +
 +    @Query("SELECT * FROM contact ORDER BY lastName ASC")
 +    fun getContactsOrderByLastName() : Flow<List<Contact>>
 +
 +    @Query("SELECT * FROM contact ORDER BY phoneNumber ASC")
 +    fun getContactsOrderByPhoneNumber() : Flow<List<Contact>>
 +}
 +</file>
android/room을사용하여데이터보관.1722252753.txt.gz · 마지막으로 수정됨: 2024/07/29 20:32 저자 이거니맨