plugins {
//...
id 'kotlin-kapt'
}
//...
dependencies {
//...
def room_version = "2.5.1"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
kapt "androidx.room:room-compiler:$room_version"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"
}
//CREATE TABLE student_table (student_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
@Entity(tableName = "student_table") student_table로 지정함
data class Student (
@PrimaryKey
@ColumnInfo(name = "student_id")
val id: Int,
val name: String
)
@Dao
interface MyDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertStudent(student: Student)
@Query("SELECT * FROM student_table")
fun getAllStudents(): LiveData<List<Student>>
@Query("SELECT * FROM student_table WHERE name = :sname")
suspend fun getStudentByName(sname: String): List<Student>
@Delete
suspend fun deleteStudent(student: Student)
// ...
}
RoomDatabase를 상속하는 클래스 생성
@Database 애노테이션에 포함되는 Entity들과 데이터베이스의 version 저장
@Database(entities = [
Student::class,
ClassInfo::class,
Enrollment::class,
Teacher::class
],
version = 1)
abstract class MyDatabase : RoomDatabase() {
//DAO를 가져올 수 있는 getter 메소드
//(실제 메소드 정의는 자동으로 생성됨)
abstract fun getMyDao() : MyDAO
companion object {
private var INSTANCE: MyDatabase? = null
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE student_table ADD COLUMN last_update INTEGER")
}
}
private val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE class_table ADD COLUMN last_update INTEGER")
}
}
//SingleTon 패턴 사용
//(Room 클래스의 객체 생성은 Room.databaseBuilder() 호출)
fun getDatabase(context: Context) : MyDatabase {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context, MyDatabase::class.java, "school_database")
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
.build()
}
return INSTANCE as MyDatabase
}
}
}