우선 프로젝트를 생성후 가장 먼저 해야할 일은 Room 설정 준비를 하는것입니다.
해당 프로젝트에서는 Gradle Version Catalog 사용 중이라 이에 맞춰 설명하겠습니다.
libs.version.toml파일 수정[versions]
room = "2.5.2"
[libraries]
room-runtime = { module = "androidx.room:room-runtime", version.ref = "room" }
room-compiler = { module = "androidx.room:room-compiler", version.ref = "room" }
room-ktx = { module = "androidx.room:room-ktx", version.ref = "room" }
[plugins]
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-kapt = { id = "org.jetbrains.kotlin.kapt", version.ref = "kotlin" }
build.gradle.kts파일 수정plugins {
id("org.jetbrains.kotlin.kapt") // KAPT 추가
}
dependencies {
// Room dependencies
implementation(libs.room.runtime)
kapt(libs.room.compiler) // Annotation Processor
implementation(libs.room.ktx) // Coroutines 지원
}
추가한 부분만 따로 작성했습니다.
여기서 kapt라는 것을 추가했는데 해당 기능을 설명하겠습니다.
kaptRoom Database는 애노테이션(@Entity, @Dao)등ㄹ을 기반으로 코드를 생성하므로, 이를 컴파일 . 시처리하기 위해 kapt가 필요합니다.엔티티는 JPA랑 비슷한 형식 이였습니다.
이전 포스트에 적은 ERD기준으로 만들었습니다.
@Entity(
tableName = "memo",
foreignKeys = [
androidx.room.ForeignKey(
entity = MemoCategory::class,
parentColumns = ["categoryId"],
childColumns = ["categoryId"],
onDelete = androidx.room.ForeignKey.SET_NULL // 카테고리 삭제 시 categoryId를 NULL로 설정
)
]
)
data class Memo (
@PrimaryKey(autoGenerate = true)
val memoId: Int = 0, //기본키, 자동 증가
val title: String, //메모 제목
val content: String, //메모 내용
val createdAt: Long, //작성 날짜 (타임 스탬프)
val isFavorite: Boolean = false //즐겨찾기 여부
)
위 코드에 대해 조금 설명 하겠습니다.
JPA에서는 @entity, @id, @ManyToOne, @JoinColumn등 어노테이션으로 객체 간 연관 관계를 설정하고 이를 기반으로 JPA가 데이터베이스 테이블 및 외래키를 관리한다면
Room에서는 @Entity어노테이션 안의 foreignKeys옵션으로 외래키를 설정합니다.
@Entity(tableName = "memo_category")
data class MemoCategory (
@PrimaryKey(autoGenerate = true)
val categoryId: Int = 0, //기본키, 자동증가
val name: String, //카테고리 이름
val description: String? = null // 선택적 설명 (nullable)
)
@Entity(
tableName = "cart_list",
foreignKeys = [
ForeignKey(
entity = Cart::class,
parentColumns = ["cartId"],
childColumns = ["cartId"],
onDelete = ForeignKey.CASCADE // Cart 삭제 시 CartList도 삭제
)
]
)
data class CartList(
@PrimaryKey(autoGenerate = true)
val cartListId: Int = 0, //기본키
val CartId: Int, //외래키
val content: String, //장바구니 항목 내용
val quantity: Int = 1, //항복 수량
val isCompleted: Boolean = false // 항목 완료 여부
)
@Entity(tableName = "cart")
data class Cart(
@PrimaryKey(autoGenerate = true)
val cartId: Int = 0, // 기본키
val title: String, //장바구니 제목
val startDate: Long, //장바구니 생성일
val endDate: Long? = null, //장바구니 완료일 (nullable)
val isCompleted: Boolean = false //장바구니 완료 여부
)
@Entity(tableName = "to_do_list")
data class ToDoList(
@PrimaryKey(autoGenerate = true)
val toDoId: Int = 0, //기본키
val title: String, //할 일 제목
val description: String?, //할 일 내용
val createdAt:Long, //생성 날짜
val isCompleted: Boolean = false, //완료 ㅇ여부
val priority: Int = 0 //우선순위 (낮은 숫자가 높은 우선 순위)
)