안녕하세요! 오늘은 안드로이드 앱 개발에서 로컬 데이터베이스를 효율적으로 관리할 수 있는 Room Persistence Library 사용법을 코드 예시와 함께 자세히 알아보겠습니다. Room DB는 SQLite를 추상화하여 개발자가 더욱 쉽고 안전하게 데이터베이스를 다룰 수 있도록 도와줍니다.
Room DB란?
Room은 SQLite를 기반으로 하는 ORM(Object Relational Mapping) 라이브러리입니다. SQLite를 직접 사용하는 것보다 다음과 같은 장점을 제공합니다.
- 컴파일 시간 검증: SQL 쿼리의 문법 오류를 컴파일 시간에 발견하여 런타임 오류를 줄입니다.
- 간편한 데이터 접근: DAO(Data Access Object)를 통해 데이터베이스에 쉽게 접근하고 조작할 수 있습니다.
- 라이브 데이터 연동: LiveData와 RxJava를 지원하여 데이터 변경을 실시간으로 감지하고 UI를 업데이트할 수 있습니다.
Room DB 구성 요소
Room DB는 크게 3가지 구성 요소로 이루어져 있습니다.
- Entity: 데이터베이스 테이블을 나타내는 클래스입니다.
- DAO: 데이터베이스에 접근하고 데이터를 조작하는 메서드를 정의하는 인터페이스입니다.
- Database: Room 데이터베이스 인스턴스를 생성하고 DAO를 제공하는 추상 클래스입니다.
Room DB 사용 예시
다음은 Room DB를 사용하여 간단한 메모 앱을 만드는 예시 코드입니다.
1. 의존성 추가
build.gradle (Module:app) 파일에 Room DB 관련 의존성을 추가합니다.
dependencies {
implementation("androidx.room:room-runtime:2.6.1")
kapt("androidx.room:room-compiler:2.6.1")
implementation("androidx.room:room-ktx:2.6.1") // 코틀린 확장
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.6.1") // 라이브 데이터
}
2. Entity 생성
Note.kt 파일을 생성하고 다음과 같이 코드를 작성합니다.
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val title: String,
val content: String
)
3. DAO 생성
NoteDao.kt 인터페이스를 생성하고 다음과 같이 코드를 작성합니다.
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface NoteDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(note: Note)
@Update
suspend fun update(note: Note)
@Delete
suspend fun delete(note: Note)
@Query("SELECT * FROM notes")
fun getAllNotes(): LiveData<List<Note>>
}
4. Database 생성
NoteDatabase.kt 추상 클래스를 생성하고 다음과 같이 코드를 작성합니다.
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class NoteDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
companion object {
@Volatile
private var INSTANCE: NoteDatabase? = null
fun getDatabase(context: Context): NoteDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
NoteDatabase::class.java,
"note_database"
).build()
INSTANCE = instance
instance
}
}
}
}
5 1 . ViewModel 생성
NoteViewModel.kt 클래스를 생성하고 다음과 같이 코드를 작성합니다.
import androidx.lifecycle.*
import kotlinx.coroutines.launch
class NoteViewModel(private val noteDao: NoteDao) : ViewModel() {
val allNotes: LiveData<List<Note>> = noteDao.getAllNotes()
fun insert(note: Note) = viewModelScope.launch {
noteDao.insert(note)
}
fun update(note: Note) = viewModelScope.launch {
noteDao.update(note)
}
fun delete(note: Note) = viewModelScope.launch {
noteDao.delete(note)
}
}
class NoteViewModelFactory(private val noteDao: NoteDao) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(NoteViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return NoteViewModel(noteDao) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
6. Activity 또는 Fragment에서 사용
Activity 또는 Fragment에서 다음과 같이 ViewModel을 초기화하고 데이터를 사용합니다.
// ...
val noteDao = NoteDatabase.getDatabase(application).noteDao()
val viewModelFactory = NoteViewModelFactory(noteDao)
val viewModel = ViewModelProvider(this, viewModelFactory).get(NoteViewModel::class.java)
viewModel.allNotes.observe(viewLifecycleOwner) { notes ->
// 노트 목록 업데이트
}
viewModel.insert(Note(title = "제목", content = "내용"))
// ...
추가 팁
- Room DB는 마이그레이션을 지원하여 데이터베이스 스키마 변경 시 데이터를 안전하게 유지할 수 있습니다.
- Room DB와 함께 LiveData, ViewModel, Coroutines를 사용하면 더욱 효율적인 앱 개발이 가능합니다.
- Room DB 공식 문서와 다양한 예제 코드를 참고하여 더 많은 기능을 활용해 보세요.
Room DB를 사용하면 안드로이드 앱에서 로컬 데이터베이스를 더욱 쉽고 안전하게 관리할 수 있습니다. 위 예시 코드를 참고하여 자신만의 앱을 개발해 보세요!
'프로그래밍' 카테고리의 다른 글
안드로이드 Retrofit으로 로또 당첨 번호 JSON 데이터 가져오기: 1000회차 예시 (0) | 2025.03.20 |
---|---|
안드로이드 Retrofit으로 로또 당첨 정보 가져오기: 크롤링 예시 코드 (0) | 2025.03.20 |
프래그먼트 안의 프래그먼트 네비게이션, 데이터 바인딩으로 더욱 깔끔하게! (0) | 2025.03.20 |
안드로이드 프래그먼트 네비게이션, 데이터 바인딩으로 더 효율적으로! (0) | 2025.03.20 |
Jsoup으로 정보 크롤링하기: 초보자 가이드 (로또 사이트 예시) (1) | 2025.03.17 |