0Pricing
Android Academy · 강의

Room 데이터베이스

Room으로 구조화된 데이터를 로컬에 저장합니다. Entity, DAO, Database 클래스를 정의하고 SQL로 조회하며 LiveData 또는 Flow로 결과를 관찰합니다.

Room 데이터베이스은(는) CoddyKit의 무료 Android Academy 강의입니다. 이것은 6개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Android Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Android Academy 강의에는 총 6개의 강의가 포함되어 있습니다.

Room이란 무엇인가요

Room은 Google이 Android에 사용하도록 권장하는 영구 저장 라이브러리입니다. SQLite를 감싸며 다음 기능을 제공합니다.

  • 컴파일 시점에 검증되는 타입 안전 SQL 쿼리
  • 코틀린 코루틴 지원
  • LiveData / Flow 통합
  • 스키마 변경을 위한 마이그레이션 지원

Room의 세 가지 구성 요소

Room은 세 가지 주석으로 구성됩니다.

  • @Entity — 데이터베이스 테이블에 매핑되는 데이터 클래스
  • @Dao (데이터 접근 객체) — SQL 쿼리가 포함된 인터페이스
  • @Database — 모든 요소를 연결하는 기본 데이터베이스 클래스

Room 종속 항목 추가

app/build.gradle에 Room을 추가하세요.

// app/build.gradle
plugins {
    id 'kotlin-kapt'  // needed for Room annotation processor
}

dependencies {
    val roomVersion = "2.6.1"
    implementation "androidx.room:room-runtime:$roomVersion"
    kapt "androidx.room:room-compiler:$roomVersion"
    implementation "androidx.room:room-ktx:$roomVersion" // coroutine support
}

Entity 정의하기

데이터베이스 테이블을 만들려면 데이터 클래스에 @Entity를 지정하세요.

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 body: String,
    val createdAt: Long = System.currentTimeMillis()
)

// Each field = one column in the database table
// @PrimaryKey autoGenerate = Room assigns the id automatically

DAO 만들기

DAO 인터페이스에 쿼리를 정의하세요. 구현은 Room이 대신 생성합니다.

import androidx.room.*
import kotlinx.coroutines.flow.Flow

@Dao
interface NoteDao {

    @Query("SELECT * FROM notes ORDER BY createdAt DESC")
    fun getAllNotes(): Flow<List<Note>>  // emits new list whenever data changes

    @Query("SELECT * FROM notes WHERE id = :noteId")
    suspend fun getNoteById(noteId: Int): Note?

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(note: Note)

    @Update
    suspend fun update(note: Note)

    @Delete
    suspend fun delete(note: Note)
}

데이터베이스 만들기

@Database 클래스는 Room의 진입점입니다. 한 번만 만들고 싱글턴으로 유지하세요.

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import android.content.Context

@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 getInstance(context: Context): NoteDatabase {
            return INSTANCE ?: synchronized(this) {
                Room.databaseBuilder(
                    context.applicationContext,
                    NoteDatabase::class.java,
                    "note_database"
                ).build().also { INSTANCE = it }
            }
        }
    }
}

ViewModel에서 Room 사용하기

코루틴을 사용하여 ViewModel에 DAO를 연결하세요.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class NoteViewModel(private val dao: NoteDao) : ViewModel() {

    val notes = dao.getAllNotes()  // Flow — auto-updates when DB changes

    fun addNote(title: String, body: String) {
        viewModelScope.launch {
            dao.insert(Note(title = title, body = body))
        }
    }

    fun deleteNote(note: Note) {
        viewModelScope.launch {
            dao.delete(note)
        }
    }
}

UI에서 Room 데이터 관찰하기

Activity 또는 Fragment에서 Room의 Flow를 수집하세요.

import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

class NoteActivity : AppCompatActivity() {
    private val viewModel: NoteViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ...

        lifecycleScope.launch {
            viewModel.notes.collect { notes ->
                adapter.submitList(notes)  // update RecyclerView
            }
        }
    }
}

데이터베이스 마이그레이션

Entity를 변경할 때(열 추가, 테이블 이름 변경 등)는 기존 사용자 데이터가 손실되지 않도록 마이그레이션을 제공해야 합니다.

@Database(version = 2)에서 버전 번호를 증가시키고, 이전 스키마를 새 스키마로 변환하는 SQL이 포함된 Migration 객체를 정의하세요.

빠른 확인

인터페이스 메서드를 SQL SELECT 쿼리로 표시하는 Room 주석은 무엇인가요?

복습: Room 데이터베이스

이제 로컬 데이터 영구 저장 기능이 있는 앱을 만들 수 있습니다.

  • @Entity — 데이터 클래스 → 데이터베이스 테이블
  • @Dao — @Query, @Insert, @Delete가 포함된 인터페이스
  • @Database — 싱글턴 진입점
  • 실시간 업데이트를 위해 DAO에서 Flow<List>를 반환합니다.
  • viewModelScope.launch를 사용하여 ViewModel에서 DAO를 호출합니다.

다음: 콜백 없이 코루틴으로 비동기 코드를 작성해 보세요.

자주 묻는 질문

“Room 데이터베이스” 강의는 무료인가요?

네 — “Room 데이터베이스” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Android Academy 강의 전체를 잠금 해제할 수 있습니다. Android Academy 강의에는 총 6개의 강의가 포함되어 있습니다.

“Room 데이터베이스”에서 뭘 배우나요?

Room으로 구조화된 데이터를 로컬에 저장합니다. Entity, DAO, Database 클래스를 정의하고 SQL로 조회하며 LiveData 또는 Flow로 결과를 관찰합니다. 브라우저에서 직접 실행하는 실습 코드로 Android Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Android Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Android Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 2번째 강의입니다.

“Room 데이터베이스” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Android Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Android Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. ViewModel과 LiveData
  2. Room 데이터베이스
  3. 코루틴과 일시 중단 함수
  4. 리포지터리 패턴
  5. Navigation Component
  6. Hilt를 사용한 의존성 주입
← Android Academy(으)로 돌아가기