(1) database
(2) entity
(3) DAO(Data Access Object)
plugins {
...
id 'kotlin-kapt'
}
...
dependencies {
def room_version = "최신 버전"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
implementation "androidx.room:room-rxjava2:$room_version"
implementation "androidx.room:room-guava:$room_version"
implementation "androidx.room:room-testing:$room_version"
...
}
android {
...
defaultConfig {
...
javaCompileOptions {
annotationProcessorOptions {
arguments = [
"room.schemaLocation":"$projectDir/schemas".toString(),
"room.incremental":"true",
"room.expandProjection":"true"]
}
}
}
}
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "user_table", ignoredColumns = ["age"])
data class User (
@PrimaryKey(autoGenerate = true)
var id: Int = 0, // 고유 ID값
@ColumnInfo(name = "first_name")
var firstName: String = "",
@ColumnInfo(name = "last_name")
var lastName: String = "",
var age: String = ""
)
(1) Entity 애노테이션
(2) 테이블 이름
(3) 기본키
(4) 컬럼명
(5) 필드 무시
@Entity(
foreignKeys = [
ForeignKey(
entity = User::class,
parentColumns = ["id"],
childColumns = ["user_id"])
]
)
data class Book (
@PrimaryKey
var bookId: Int = 0,
var title: String = "",
@ColumnInfo(name = "user_id")
var userId: String = ""
)
@Entity
data class Playlist(
@PrimaryKey
val id: Int,
val name: String
)
@Entity
data class Song(
@PrimaryKey
val id: Int,
val songName: String,
val artistName: String
)
@Entity(
tableName = "playlist_song_join",
primaryKeys = ["playlistId", "songId"],
foreignKeys = [
ForeignKey(entity = Playlist::class,
parentColumns = ["id"],
childColumns = ["playlistId"]),
ForeignKey(entity = Song::class,
parentColumns = ["id"],
childColumns = ["songId"])]
)
data class PlaylistSongJoin (
val playlistId : Int,
val songId : Int
)